使用SpringCloud搭建一個(gè)簡(jiǎn)單的項(xiàng)目

因?yàn)橐芯糠植际绞聞?wù) 所以搭建一個(gè)簡(jiǎn)單的SpringCloud的項(xiàng)目 來(lái)進(jìn)行事務(wù)相關(guān)的測(cè)試 中間出現(xiàn)了一些小問(wèn)題 在這里記錄一下創(chuàng)建項(xiàng)目的整個(gè)過(guò)程

  • 創(chuàng)建EurekServer
    創(chuàng)建一個(gè)springboot項(xiàng)目 并引入依賴web eurekserver hystrix-dashboard,'security'
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

修改配置文件 更改端口號(hào) 以及配置security

server:
  port: 8761

spring:
  application:
    name: registry
  security:
    user:
      name: zhou
      password: 12345678

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    serviceUrl:
      defaultZone: http://zhou:12345678@localhost:${server.port}/eureka/

然后修改啟動(dòng)類

@SpringBootApplication
@EnableEurekaServer
@EnableHystrixDashboard
public class RegistryApplication {

    public static void main(String[] args) {
        SpringApplication.run(RegistryApplication.class, args);
    }

}

然后建立一個(gè)zuul的網(wǎng)關(guān) 引入pom文件

   <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>

對(duì)yml文件進(jìn)行配置 修改端口號(hào) 增加application name

server:
  port: 8888

spring:
  application:
    name: proxy
eureka:
  client:
    serviceUrl:
      defaultZone:  http://zhou:12345678@localhost:8761/eureka

然后寫一個(gè)user的項(xiàng)目來(lái)進(jìn)行測(cè)試 使用的是h2jpa
建立domain

@Entity(name = "customer")
public class Customer {
    @Id
    @GeneratedValue
    private Long userId;
    private String password;
    private String userName;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

建立CustomerRepositry 因?yàn)榫褪且粋€(gè)測(cè)試 所以只是繼承了JpaRepository

public interface CustomerRepositry extends JpaRepository<Customer,Long> {

}

service

@Service
public class CustomerService {
    @Resource
    private CustomerRepositry customerRepositry;

    //根據(jù)id 查詢用戶
    public Optional<Customer> getCustomerById(Long id){
        return customerRepositry.findById(id);
    }
    //查詢用戶信息
    public List<Customer> getAllCustomer(){
        return customerRepositry.findAll();
    }
    //保存用戶信息
    public void save(Customer customer){
        customerRepositry.save(customer);
    }
}

controller

@RestController
@RequestMapping("/user/test")
public class CustomerController {
    @Resource
    private CustomerService customerService;
    @Resource
    private OrderClient orderClient;

    @PostConstruct
    public void init(){
        Customer customer = new Customer();
        customer.setUserId(1L);
        customer.setUserName("KrisWu");
        customer.setPassword("123456");
        customerService.save(customer);
    }

    @RequestMapping("getCustomer")
    public List<Customer> getCustomer(){
        return customerService.getAllCustomer();
    }

    @RequestMapping("getOrder")
    @HystrixCommand
    public Map getOrder(){
        Optional<Customer> customer = customerService.getCustomerById(1L);
        String orderDetail = orderClient.getMyOrder(1L);
        Map map = new HashMap();
        map.put("customer",customer);
        map.put("orderDetail",orderDetail);
        return map;
    }

啟動(dòng)項(xiàng)目 出現(xiàn)了報(bào)錯(cuò)

ERROR 11612 --- [tbeatExecutor-0] com.netflix.discovery.DiscoveryClient    : *****:***** - was unable to send heartbeat!

這個(gè)錯(cuò)誤是在2.0以上會(huì)出現(xiàn)的。是因?yàn)閟ecurity默認(rèn)啟用了csrf檢驗(yàn),要在eurekaServer端配置security的csrf檢驗(yàn)為false。
所以在repostory中新建一個(gè)config文件

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        super.configure(http);
    }
}

然后通過(guò)proxy的地址來(lái)訪問(wèn)user的項(xiàng)目
訪問(wèn)地址(http://localhost:8888/user/user/test/getCustomer)
然后發(fā)現(xiàn)可以顯示增加的用戶信息

通過(guò)zuul訪問(wèn)

然后再新建一個(gè)order的項(xiàng)目 想要達(dá)到的想過(guò)是可以在user的項(xiàng)目中 直接調(diào)用order中的方法 這里和user基本上是差不多的 就不貼代碼了
重要的地方是在user的項(xiàng)目中 新建一個(gè)類OrderClient

@FeignClient(value = "order",path = "/order/test")
public interface OrderClient {
    @GetMapping("/{id}")
    String getMyOrder(@PathVariable(name = "id")Long id);
}

主要就是通過(guò)這個(gè)類進(jìn)行連接
然后啟動(dòng)項(xiàng)目 進(jìn)行測(cè)試


image.png

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容