spring boot 2.0.3+spring cloud (Finchley)4、熔斷器Hystrix


在分布式系統中服務與服務之間的依賴錯綜復雜,一種不可避免的情況就是某些服務會出現故障,導致依賴於他們的其他服務出現遠程調度的線程阻塞。某個服務的單個點的請求故障會導致用戶的請求處於阻塞狀態,最終的結果是整個服務的線程資源消耗殆盡。由於服務的依賴性,會導致依賴於該故障服務的其他服務也處於線程阻塞狀態,最終導致這些服務的線程資源消耗殆盡,知道不可用,從而導致整個服務系統不可用,即雪崩效應。為了防止雪崩效應,產生了熔斷器模型。

Hystrix是Netflix公司開源的一個項目,提供了熔斷器功能,能阻止分布式系統中出現聯動故障。Hystrix是通過隔離服務的訪問點阻止聯動故障的,並提供了故障解決方案,從而提高了整個分布式系統的彈性。

當服務的某個API接口的失敗次數在一定時間內小於設定的閾值時,熔斷器處於關閉狀態,該API接口正常提供服務。當該API接口處理請求的失敗次數大於設定的閾值時,hystrix判定該API接口出現了故障,打開熔斷器,這時請求該API接口會執行快速失敗的邏輯(即fallback回退的邏輯),不執行業務邏輯,請求的線程不會處於阻塞狀態。處於打開狀態的熔斷器,一段時間后會處於半打開狀態,並將一定數量的請求執行正常邏輯,剩余的請求會執行快速失敗,若執行正常邏輯的請求失敗了,則熔斷器繼續打開,若成功了,則關閉熔斷器。這樣熔斷器就具有了自我修復的能力。

在RestTemplate和Ribbon上使用熔斷器

需要已經成功配置Ribbon,可參考:spring boot 2.0.3+spring cloud (Finchley)2、搭建負載均衡Ribbon (Eureka+Ribbon+RestTemplate)

在eureka-ribbon-client工程中,使用了RestTemplate調用了eureka-client的“/hi”API接口,並使用ribbon做了負載均衡,在此基礎上加入Hystrix熔斷器功能。在pom文件中加入Hystrix起步依賴spring-cloud-starter-netflix-hystrix

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cralor</groupId>
    <artifactId>eureka-ribbon-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eureka-ribbon-client</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.cralor</groupId>
        <artifactId>chap8-hystrix</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在項目啟動類加上@EnableHystrix注解,開啟hystrix熔斷器功能

@EnableHystrix
@SpringBootApplication
public class EurekaRibbonClientApplication {

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

修改RibbonService代碼,在hi()方法上加上@HystrixCommand注解。有了該注解hi()方法就啟用了Hystrix熔斷器的功能,其中,fallbackMethod為處理回退(fallback)邏輯的方法。在本例子,直接返回了一個字符串。在熔斷器打開的狀態下,會執行fallback邏輯。fallback的邏輯最好是返回一些靜態的字符串,不需要處理復雜的邏輯,也不會遠程調用其他服務,這樣方便執行快速失敗,釋放線程資源。如果一定要在fallback邏輯中遠程調用其他服務,最好在遠程調用其他服務時,也加上熔斷器。

@Service
public class RibbonService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String hi(String name){
        return restTemplate.getForObject("http://eureka-client/hi?name="+name,String.class);
    }
    public String hiError(String name){
        return "hi,"+name+",sorry,error!";
    }
}

RibbonConfig類

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

RibbonController類

@RestController
public class RibbonController {
    @Autowired
    private RibbonService ribbonService;

    @GetMapping("/hi")
    public String hi(@RequestParam(required = false,defaultValue = "cralor") String name){
        return ribbonService.hi(name);
    }
}

依次啟動eureka-server、eureka-client和eureka-ribbon-client。在瀏覽器訪問http://localhost:8764/hi,會顯示

關閉eureka-client,使其處於不可以狀態,此時eureka-ribbon-client無法調用eureka-client的“/hi”接口,訪問http://localhost:8764/hi

 由此可見,當eureka-client不可用時,調用eureka-ribbon-client的”/hi“接口會進入RibbonSerivce類的”/hi“方法。由於eureka-client沒有響應,判定不可用,開啟了熔斷器,最后進入了fallbackMethod的邏輯。之后的請求會直接執行fallbackMethod的邏輯。

在Feign上使用熔斷器

Feign的起步依賴中已經引入了Hystrix的依賴,只需要在eureka-feign-client工程的配置文件中開啟hystrix功能即可,

server:
  port: 8765
spring:
  application:
    name: eureka-feign-client
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
feign:
  hystrix:
    enabled: true

修改EurekaClientFeign代碼,在@FeignClient注解的fallback配置加上快速失敗的處理類。該處理類是作為geign熔斷器的邏輯處理類,必須實現被@FeignClient修飾的接口。

EurekaClientFeign類

@Component
@FeignClient(value = "eureka-client",configuration = FeignConfig.class,fallback = HiHystrix.class)
public interface EurekaClientFeign {
    @GetMapping(value = "/hi")
    String sayHiFromClientEureka(@RequestParam(value = "name")String name);
}

HiHystrix 類

@Component
public class HiHystrix implements EurekaClientFeign {

    @Override
    public String sayHiFromClientEureka(String name) {
        return "hi,"+name+",sorry.error!";
    }
}

FeignConfig類

@Configuration
public class FeignConfig {
    @Bean
    public Retryer feignRetryer(){
        return new Retryer.Default(100,TimeUnit.SECONDS.toMillis(1),5);
    }
}

HiService 類

@Service
public class HiService {
    @Autowired
    EurekaClientFeign eurekaClientFeign;

    public  String sayHi(String name){
        return eurekaClientFeign.sayHiFromClientEureka(name);
    }
}

HiController 類

@RestController
public class HiController {
    @Autowired
    HiService hiService;

    @GetMapping("/hi")
    public String sayHi(@RequestParam(defaultValue = "cralor",required = false)String name){
        return hiService.sayHi(name);
    }
}

啟動工程eureka-server、eureka-client和eureka-feign-client,瀏覽器訪問http://localhost:8765/hi

關閉eureka-client

由此可見,當eureka-client不可以時,eureka-feign-client進入了fallback的邏輯處理類HiHystrix,由這個類來執行熔斷器打開時的處理邏輯。

使用Hystrix Dashboard監控熔斷器的狀態

Hystrix Dashboard時監控Hystrix的熔斷器的一個組件,提供了數據監控和友好的展示界面。

在Rest Template中使用Hystrix Dashboard

在eureka-ribbon-client工程的pom文件加上Actuator、Hystrix 和Hystrix Dashboard的起步依賴,這三個依賴是必需的。

<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-hystrix</artifactId>
        </dependency>

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

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

修改配置文件,啟動actuator監控

server:
port: 8764
spring:
application:
name: eureka-ribbon-client
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

#springboot2.0. 的配置項為:
#actuator端口
management:
server:
port: 9001
endpoints:
web:
# base-path: / #修改訪問路徑 2.0之前默認是/ 2.0默認是 /actuator 可以通過這個屬性值修改
exposure:
include: '*' #開放所有頁面節點 默認只開啟了health、info兩個節點

在程序啟動類加上@EnableHystrixDashboard注解,

@EnableHystrixDashboard
@EnableHystrix
@SpringBootApplication
public class EurekaRibbonClientApplication {

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

依次啟動eureka-server、eureka-client和eureka-ribbon-client。在瀏覽器訪問先訪問http://localhost:8764/hi,然后再訪問http://localhost:9001/actuator/hystrix.stream,瀏覽器會顯示熔斷器的數據指標

在瀏覽器訪問http://localhost:8764/hystrix,注意:端口號為具體服務對應的端口號而不是Eureka Server的端口號

 

依次填寫http://localhost:9001/actuator/hystrix.stream、2000、cralor(隨意填寫),點擊 moniter

 

該頁面顯示了熔斷器的谷中數據指標,這些數據指標含義如圖,該圖來自於Hystrix官方文檔,文檔地址:https://github.com/Netflix/Hystrix/wiki

 

 在Feign中使用Hystrix Dashboard

在eureka-feign-client的pom文件加上Actuator、Hystrix和Dashboard的起步依賴,(Feign自帶的Hystrix依賴不是起步依賴,還需要加上起步依賴)

 <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-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</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-actuator</artifactId>
        </dependency>

啟動類加上注解@EnableHystrixDashboard,@EnableHystrix

@EnableHystrixDashboard
@EnableHystrix
@EnableFeignClients
@SpringBootApplication
public class EurekaFeignClientApplication {

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

啟動即可,其他步驟跟ribbon一樣。

使用Turbine聚合監控

 在使用Hystrix Dashboard組件監控服務的熔斷器狀況時,每個服務都有一個Hystrix Dashboard主頁,服務數量過多時,監控非常不方便。Netflix開源了另一個組件Turbine,用於聚合多個Hystrix Dashboard,將數據顯示在一個頁面上,集中監控。

新建一個module工程eureka-monitor-client,作為Turbine聚合監控的工程。pom文件引入相關actuator、hystrix dashboard和turbine的起步依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cralor</groupId>
    <artifactId>eureka-monitor-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eureka-monitor-client</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.cralor</groupId>
        <artifactId>chap8-hystrix</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

修改配置文件

server:
  port: 8769
spring:
  application:
    name: service-turbine
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

#springboot2.0. 的配置項為:
#actuator端口
management:
#  server:
#    port: 9007
  endpoints:
    web:
#      base-path: /monitor #修改訪問路徑  2.0之前默認是/   2.0默認是 /actuator  可以通過這個屬性值修改
      exposure:
        include: '*'  #開放所有頁面節點  默認只開啟了health、info兩個節點

turbine:
  aggregator:
    cluster-config: default     #需要監控的服務集群名
  app-config: eureka-ribbon-client,eureka-feign-client    #需要監控的服務名
  cluster-name-expression: new String("default")
#  instanceUrlSuffix:
#      default: actuator/hystrix.stream    #key是clusterConfig集群的名字,value是hystrix監控的后綴,springboot2.0為actuator/hystrix.stream

在啟動類加上注解

@EnableTurbine
@EnableHystrixDashboard
@SpringBootApplication
public class EurekaMonitorClientApplication {

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

啟動工程eureka-server、eureka-client、eureka-ribbon-client、eureka-feign-client和eureka-monitor-client,在瀏覽器訪問http://localhost:8764/hi,http://localhost:8765/hi,在瀏覽器打開http://localhost:8764/hystrix(端口號8764、8765、8769都可以),依次填入http://localhost:8769/turbine.stream,2000,cralor,點擊”monitor“,

可以看到這個頁面聚合了eureka-ribbon-client和eureka-feign-client的Hystrix Dashboard數據。

 

參考:https://windmt.com/2018/04/15/spring-cloud-4-hystrix/

https://windmt.com/2018/04/16/spring-cloud-5-hystrix-dashboard/

https://windmt.com/2018/04/17/spring-cloud-6-turbine/

 

 

案例代碼地址:https://github.com/cralor7/springcloud

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM