1. 程式人生 > 實用技巧 >springcloud學習入門

springcloud學習入門

Springcloud入門學習筆記

1. 專案初始化配置

1. 1. 新建maven工程

使用idea建立maven專案

1. 2. 在parent專案pom中匯入以下依賴

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4.RELEASE</version>
</parent>
<properties>
    <spring.cloud-version>Hoxton.SR8</spring.cloud-version>
</properties>
<dependencyManagement>
<dependencies>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>${spring.cloud-version}</version>
    <type>pom</type>
    <scope>import</scope>
  </dependency>
</dependencies>
</dependencyManagement>

2. Eureka使用

2. 1. 建立子module,命名為eureka-server

2. 2. 在eureka-server中新增以下依賴

<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.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. 3. 在application.yml中新增以下配置

server:
  port: 8900 #應用的埠號
eureka:
  client:
    service-url:
      defaultZone: http://user:123@localhost:8900/eureka #eureka服務的的註冊地址
    fetch-registry: false #是否去註冊中心拉取其他服務地址
    register-with-eureka: false #是否註冊到eureka
spring:
  application:
    name: eureka-server   #應用名稱 還可以用eureka.instance.hostname = eureka-server
  security: #配置自定義Auth賬號密碼
    user:
      name: user
      password: 123

2. 4. 在啟動類上架註解

@SpringBootApplication
@EnableEurekaServer

在啟動類中加入以下方法,防止spring的Auth攔截eureka請求

@EnableWebSecurity
    static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().ignoringAntMatchers("/eureka/**");
            super.configure(http);
        }
    }

2. 5. 建立module名為provider-user為服務提供者

2. 5. 1. 在pom中新增以下依賴
<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-client</artifactId>
</dependency>
2. 5. 2. application.yml配置
server:
  port: 7900 #程式啟動入口
spring:
  application:
    name: provider-user #應用名稱
eureka:
  client:
    service-url:
      defaultZone: http://user:123@${eureka.instance.hostname}:${server.port}/eureka/
2. 5. 3. 啟動類加註解
@SpringBootApplication
@EnableEurekaClient

Controller相關程式碼如下:

@RestController
public class UserController {
    @GetMapping (value = "/user/{id}")
    public User getUser(@PathVariable Long id){
        User user = new User();
        user.setId(id);
        user.setDate(new Date());
        System.out.println("7900");
        return user;
    }
    @PostMapping (value = "/user")
    public User getPostUser(@RequestBody User user){
        return user;
    }
}

2. 6. 建立module名為consumer-order為服務提供者

2. 6. 1. pom依賴同服務提供者
2. 6. 2. application.yml配置
server:
  port: 8010
spring:
  application:
    name: consumer-order
eureka:
  client:
    serviceUrl:
      defaultZone: http://user:123@${eureka.instance.hostname}:${server.port}/eureka/
2. 6. 3. 啟動類
@SpringBootApplication
@EnableEurekaClient
public class ConsumerApp
{
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main( String[] args )
    {
        SpringApplication.run(ConsumerApp.class,args);
    }
}
2. 6. 4. Controller層程式碼
@RestController
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;
    @GetMapping (value = "/order/{id}")
    public User getOrder(@PathVariable Long id){
        //獲取資料
        User user = new User();
        user.setId(id);
        user.setDate(new Date());
        user = restTemplate.getForObject("http://provider-user:7900/user/"+id,User.class);
        return user;
    }
}

2. 7. 啟動應用

分別啟動Eureka-server、provider-user、consumer-order三個服務

2. 8. 訪問地址

http://localhost:8900就可以看到兩個服務已經註冊到eureka註冊中心上了

2. 9. eureka高可用配置

兩個節點

#高可用配置,兩個節點
spring:
  application:
    name: eureka-server-ha
  profiles:
    active: peer1

eureka:
  client:
    serviceUrl:
      defaultZone: https://peer1/eureka/,http://peer2/eureka/
---
server:
  port: 8901
spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1

---
server:
  port: 8902
spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2

三個節點

#高可用配置,三個
spring:
  application:
    name: eureka-server-ha
  profiles:
    active: peer3
eureka:
  client:
    serviceUrl:
      defaultZone: http://peer1:8901/eureka/,http://peer2:8902/eureka/,http://peer3:8903/eureka/
---
spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1
server:
  port: 8901
---
spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2
server:
  port: 8902
---
spring:
  profiles: peer3
eureka:
  instance:
    hostname: peer3
server:
  port: 8903

3. Ribbon的使用入門

3. 1. 方式一(預設)

輪詢規則
在啟動類中restTemplate()方法加入註解@LoadBalanced
RestTemplate 是由 Spring Web 模組提供的工具類,與 SpringCloud 無關,是獨立存在的,因 SpringCloud 對 RestTemplate 進行了一定的擴充套件,所以 RestTemplate 具備了負載均衡的功能

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    return new RestTemplate();
}

在啟動類上加註解

@RibbonClient(name = "provider-user")

3. 2. 方式二(配置檔案自定義)

在application.yml中加入以下配置

#使用配置檔案方式實現負載均衡,優先順序,配置檔案>註解或java程式碼配置>cloud預設配置
provider-user:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

3. 3. 方式三(Java程式碼自定義)

自定義一個配置類,返回規則

@RibbonClient(name = "provider-user",configuration = RibbonConfiguration.class)
public class RibbonConfiguration {
    @Bean
    public IRule getRule(){
        return new RandomRule();
    }
}

4. Feign學習

什麼是feign,是宣告式的webservice客戶端,解決遠端呼叫,支援JAX-RS,即RestFulWebService

4. 1. 引入依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

4. 2. 使用註解@FeignClient編寫feign呼叫的客戶端介面

@FeignClient("provider-user")
public interface UserFeignClient {
    @RequestMapping (value = "/user/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id);
    @RequestMapping (value = "/user", method = RequestMethod.POST)
    public User postUser(@RequestBody User user);
}

4. 3. 在啟動類加註解@EnableFeignClients

4. 4. Controller層的呼叫方法

@Autowired
private UserFeignClient userFeignClient;
@GetMapping (value = "/user/{id}")
public User getUser(@PathVariable Long id){
    //獲取資料
    return this.userFeignClient.getUser(id);
}
@GetMapping (value = "/user")
public User postUser(User user){
    return this.userFeignClient.postUser(user);
}

5. hystrix學習

hystrix是Netflix的一個類庫,在微服務中,具有多層服務呼叫,主要實現斷路器模式的類庫

5. 1. 引入依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

5. 2. 在啟動類上加註解

@EnableCircuitBreaker
    1. 在Controller層類的方法上加註解,並編寫退回方法,需同名
@HystrixCommand(fallbackMethod = "findByIdFallBack")
public User getOrder(@PathVariable Long id){
    //獲取資料
    User user = new User();
    user.setId(id);
    user.setDate(new Date());
    user = restTemplate.getForObject("http://provider-user/user/"+id,User.class);
    System.out.println(Thread.currentThread().getId());
    return user;
}
public User findByIdFallBack(Long id){
    System.out.println(Thread.currentThread().getId());
    User user = new User();
    user.setId(1L);
    return user;
}

6. springboot的健康監控actuator

actuator主要用於服務健康監控,springboot 1.X和2.x有所不同,本次為2.X

6. 1. 引入依賴包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

6. 2. 配置

#健康監控配置
management:
  endpoint:
    health:
      show-details: always #是否健康監控顯示細節
  endpoints:
    web:
      exposure:
        include: hystrix.stream #hystrix保護機制,不直接暴露監控狀態
      base-path: / #暴露的端點連結

6. 3. 訪問

1.X版本

localhost:8080/health

2.X版本

localhost:8080/actuator/health

7. feign配合Hystrix使用

7. 1. 配置檔案

feign:
  hystrix:
    enabled: true # 總開關,可以通過java單獨控制client

7. 2. 啟動類註解

@EnableFeignClients

7. 3. 控制層

@RestController
public class OrderFeignController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private UserFeignNotHystrixClient userFeignNotHystrixClient;
    @GetMapping (value = "/order/{id}")
    public User getUser(@PathVariable Long id){
        //獲取資料
        return userFeignClient.getUser(id);
    }

    /**
     * 測試Feign客戶端單獨控制
     * @param id
     * @return
     */
    @GetMapping(value = "/user/{id}")
    public User getUserNotHystrix(@PathVariable Long id){
        //獲取資料
        return userFeignNotHystrixClient.getUserNotHystrix(id);
    }
}

7. 4. 兩個FeignClient

一個加了configuration一個沒有,加了可以通過註解重寫feignBuilder方法單獨控制,預設是返回HystrixFeignBuilder

@FeignClient(name = "provider-user", fallback = HystrixClientFallback.class)
public interface UserFeignClient {
    @RequestMapping (value = "/user/{id}", method = RequestMethod.GET)
    User getUser(@PathVariable Long id);
}

@Component
public class HystrixClientFallback implements UserFeignClient{
    @Override
    public User getUser(Long id) {
        System.out.println(Thread.currentThread().getId());
        User user = new User();
        user.setId(1L);
        return user;
    }
}
@FeignClient(name = "provider-user1",configuration = ConfigurationNotHystrix.class,fallback = HystrixClientNotHystrixFallback.class)
public interface UserFeignNotHystrixClient {
    @RequestMapping (value = "/user/{id}", method = RequestMethod.GET)
    User getUserNotHystrix(@PathVariable Long id);
}

@Component
public class HystrixClientNotHystrixFallback implements UserFeignNotHystrixClient{
    @Override
    public User getUserNotHystrix(Long id) {
        System.out.println(Thread.currentThread().getId());
        User user = new User();
        user.setId(1L);
        return user;
    }
}

7. 5. 配置類

@Configuration
public class ConfigurationNotHystrix {

    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder(){
        return Feign.builder();
    }
}

7. 6. 獲取異常資訊程式碼

@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

@Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
    @Override
    public HystrixClient create(Throwable cause) {
        return new HystrixClient() {
            @Override
            public Hello iFailSometimes() {
                return new Hello("fallback; reason was: " + cause.getMessage());
            }
        };
    }
}

持續更新中