SpringCloud Hystrix熔斷器使用方法介紹
Hystrix(hi si ju ke si)概述
Hystix 是 Netflix 開源的一個(gè)延遲和容錯(cuò)庫,用于隔離訪問遠(yuǎn)程服務(wù)、第三方庫,防止出現(xiàn)級聯(lián)失?。ㄑ┍溃?。
雪崩:一個(gè)服務(wù)失敗,導(dǎo)致整條鏈路的服務(wù)都失敗的情形。
Hystix 主要功能
- 隔離
- 降級
- 熔斷
- 限流
隔離
- 線程池隔離
- 信號量隔離
Hystrix 降級
Hystix 降級:當(dāng)服務(wù)發(fā)生異?;蛘{(diào)用超時(shí),返回默認(rèn)數(shù)據(jù)

Hystrix降級-服務(wù)提供方
- 在服務(wù)提供方,引入 hystrix 依賴
- 定義降級方法
- 使用 @HystrixCommand 注解配置降級方法
- 在啟動(dòng)類上開啟Hystrix功能:@EnableCircuitBreaker
初始化程序和Fiegn程序一致
需要修改的程序
package com.itheima.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* 啟動(dòng)類
*/
@EnableEurekaClient //該注解 在新版本中可以省略
@SpringBootApplication
@EnableCircuitBreaker ///開啟Hystrix功能
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class,args);
}
}
測試的程序
package com.itheima.provider.controller;
import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* Goods Controller 服務(wù)提供方
*/
@RestController
@RequestMapping("/goods")
public class GoodsController {
@Autowired
private GoodsService goodsService;
@Value("${server.port}")
private int port;
/**
* 降級:
* 1 出現(xiàn)異常
* 2 調(diào)用服務(wù)超時(shí)
* 默認(rèn)1s超時(shí)
*
*@HystrixCommand(fallbackMethod = "findOne_fallback")
* fallbackMethod 指定降級后的名稱
* @param id
* @return
*/
@GetMapping("/findOne/{id}")
@HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = {
//設(shè)置Hystrix的超時(shí)時(shí)間 默認(rèn)1s
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})///指定降級后的方法
public Goods findOne(@PathVariable("id") int id) {
///1 造個(gè)異常
//int i =3/0;
try {
Thread.sleep(2000);//sleep interrupted
} catch (InterruptedException e) {
e.printStackTrace();
}
Goods goods = goodsService.findOne(id);
goods.setTitle(goods.getTitle() + ":" + port);//將端口號,設(shè)置到了 商品標(biāo)題上
return goods;
}
/**
* 定義降級放啊
* 1 方法的返回值需要和原方法一樣
* 2 方法參數(shù)需要和原方法一樣
*/
public Goods findOne_fallback(int id) {
Goods goods = new Goods();
goods.setTitle("降級了~~~");
return goods;
}
}指定坐標(biāo)
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
Hystrix降級-服務(wù)消費(fèi)方
- feign 組件已經(jīng)集成了 hystrix 組件。
- 定義feign 調(diào)用接口實(shí)現(xiàn)類,復(fù)寫方法,即降級方法
- 在 @FeignClient 注解中使用 fallback 屬性設(shè)置降級處理類。
- 配置開啟 feign.hystrix.enabled = true
provider與Fiegin一致
application.yml修改
server:
port: 9000eureka:
instance:
hostname: localhost # 主機(jī)名
client:
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: hystrix-consumer # 設(shè)置當(dāng)前應(yīng)用的名稱。將來會(huì)在eureka中Application顯示。將來需要使用該名稱來獲取路徑
#開啟feign對hystrix支持
feign:
hystrix:
enabled: true
ConsumerApp修改
package com.itheima.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableDiscoveryClient // 激活DiscoveryClient
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients //開啟Feign的功能
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
}
修改GoodsFeignClient方法
package com.itheima.consumer.feign;
import com.itheima.consumer.domain.Goods;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "HYSTRIX-PROVIDER",fallback = GoodsFeignClientFallback.class)
public interface GoodsFeignClient {
@GetMapping("/goods/findOne/{id}")
public Goods findGoodsById(@PathVariable("id") int id);
}
復(fù)寫方法
package com.itheima.consumer.feign;
import com.itheima.consumer.domain.Goods;
import org.springframework.stereotype.Component;
/**
* Fegin 客戶端降級處理類
* 1 定義類 實(shí)現(xiàn)Feign 客戶端接口
* 2 使用@Component注解將該類的Bean加入SpringIOC容器
*/
@Component
public class GoodsFeignClientFallback implements GoodsFeignClient{
@Override
public Goods findGoodsById(int id) {
Goods goods = new Goods();
goods.setTitle("又被降級了~~");
return goods;
}
}
Hystrix 熔斷
Hystrix 熔斷機(jī)制,用于監(jiān)控微服務(wù)調(diào)用情況,當(dāng)失敗的情況達(dá)到預(yù)定的閾值(5秒失敗20次),會(huì)打開斷路器,拒絕所有請求,直到服務(wù)恢復(fù)正常為止。
- circuitBreaker.sleepWindowInMilliseconds:監(jiān)控時(shí)間
- circuitBreaker.requestVolumeThreshold:失敗次數(shù)
- circuitBreaker.errorThresholdPercentage:失敗率

//設(shè)置Hystrix的超時(shí)時(shí)間 默認(rèn)1s @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"), //監(jiān)控的時(shí)間 默認(rèn)5000ms @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "1000"), //失敗次數(shù),默認(rèn)20次 @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "2"), //失敗率 百分之50 @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "100")
Hystrix 熔斷監(jiān)控
- Hystrix 提供了 Hystrix-dashboard 功能,用于實(shí)時(shí)監(jiān)控微服務(wù)運(yùn)行狀態(tài)。
- 但是Hystrix-dashboard只能監(jiān)控一個(gè)微服務(wù)。
- Netflix 還提供了 Turbine ,進(jìn)行聚合監(jiān)控。


Turbine聚合監(jiān)控
搭建監(jiān)控模塊
1. 創(chuàng)建監(jiān)控模塊
創(chuàng)建hystrix-monitor模塊,使用Turbine聚合監(jiān)控多個(gè)Hystrix dashboard功能,
2. 引入Turbine聚合監(jiān)控起步依賴
<?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">
<parent>
<artifactId>hystrix-parent</artifactId>
<groupId>com.itheima</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>hystrix-monitor</artifactId>
<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>
<!--單獨(dú)熔斷監(jiān)控-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<!--聚合熔斷監(jiān)控-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-turbine</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-eureka-client</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>3. 修改application.yml
spring:
application.name: hystrix-monitor
server:
port: 8769
turbine:
combine-host-port: true
# 配置需要監(jiān)控的服務(wù)名稱列表
app-config: hystrix-provider,hystrix-consumer
cluster-name-expression: "'default'"
aggregator:
cluster-config: default
#instanceUrlSuffix: /actuator/hystrix.stream
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
4. 創(chuàng)建啟動(dòng)類
@SpringBootApplication
@EnableEurekaClient
@EnableTurbine //開啟Turbine 很聚合監(jiān)控功能
@EnableHystrixDashboard //開啟Hystrix儀表盤監(jiān)控功能
public class HystrixMonitorApp {
public static void main(String[] args) {
SpringApplication.run(HystrixMonitorApp.class, args);
}
}
修改被監(jiān)控模塊
需要分別修改 hystrix-provider 和 hystrix-consumer 模塊:
1、導(dǎo)入依賴:
<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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
2、配置Bean
此處為了方便,將其配置在啟動(dòng)類中。
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/actuator/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
3、啟動(dòng)類上添加注解@EnableHystrixDashboard
@EnableDiscoveryClient
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
@EnableHystrixDashboard // 開啟Hystrix儀表盤監(jiān)控功能
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/actuator/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
啟動(dòng)測試
1、啟動(dòng)服務(wù):
- eureka-server
- hystrix-provider
- hystrix-consumer
- hystrix-monitor
2、訪問:
在瀏覽器訪問http://localhost:8769/hystrix/ 進(jìn)入Hystrix Dashboard界面

界面中輸入監(jiān)控的Url地址 http://localhost:8769/turbine.stream,監(jiān)控時(shí)間間隔2000毫秒和title,如下圖

- 實(shí)心圓:它有顏色和大小之分,分別代表實(shí)例的監(jiān)控程度和流量大小。如上圖所示,它的健康度從綠色、黃色、橙色、紅色遞減。通過該實(shí)心圓的展示,我們就可以在大量的實(shí)例中快速的發(fā)現(xiàn)故障實(shí)例和高壓力實(shí)例。
- 曲線:用來記錄 2 分鐘內(nèi)流量的相對變化,我們可以通過它來觀察到流量的上升和下降趨勢。

到此這篇關(guān)于SpringCloud Hystrix熔斷器使用方法介紹的文章就介紹到這了,更多相關(guān)SpringCloud Hystrix熔斷器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringCloud Gateway動(dòng)態(tài)路由配置詳解
- Spring?Cloud?Gateway遠(yuǎn)程命令執(zhí)行漏洞分析(CVE-2022-22947)
- SpringSecurit鹽值加密的密碼驗(yàn)證以及強(qiáng)密碼驗(yàn)證過程
- Spring?Cloud?Alibaba實(shí)現(xiàn)服務(wù)的無損下線功能(案例講解)
- springcloud-gateway集成knife4j的示例詳解
- SpringCloud?Alibaba環(huán)境集成之nacos詳解
- Spring?Cloud?Ribbon?負(fù)載均衡使用策略示例詳解
- SpringCloud @RefreshScope刷新機(jī)制深入探究
- SpringCloud?@RefreshScope刷新機(jī)制淺析
- SpringCloud啟動(dòng)失敗問題匯總
- 一文吃透Spring?Cloud?gateway自定義錯(cuò)誤處理Handler
- SpringCloud Gateway路由組件詳解
- SpringCloud OpenFeign基本介紹與實(shí)現(xiàn)示例
- Spring Cloud Gateway替代zuul作為API網(wǎng)關(guān)的方法
- SpringCloud使用Feign實(shí)現(xiàn)遠(yuǎn)程調(diào)用流程詳細(xì)介紹
- SpringCloud修改Feign日志記錄級別過程淺析
- SpringCloud開啟session共享并存儲(chǔ)到Redis的實(shí)現(xiàn)
- Spring?Cloud原理以及核心組件詳解
相關(guān)文章
mybatis plus自動(dòng)生成器解析(及遇到的坑)
這篇文章主要介紹了mybatis-plus自動(dòng)生成器及遇到的坑,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Mybatis in條件傳參的三種實(shí)現(xiàn)方式(直接$,List,[])
這篇文章主要介紹了Mybatis in條件傳參的三種實(shí)現(xiàn)方式(直接$,List,[]),具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(45)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你2021-07-07
詳解Java ScheduledThreadPoolExecutor的踩坑與解決方法
最近項(xiàng)目上反饋某個(gè)重要的定時(shí)任務(wù)突然不執(zhí)行了,很頭疼,開發(fā)環(huán)境和測試環(huán)境都沒有出現(xiàn)過這個(gè)問題。定時(shí)任務(wù)采用的是ScheduledThreadPoolExecutor,后來一看代碼發(fā)現(xiàn)踩了一個(gè)大坑。本文就來和大家聊聊這次的踩坑記錄與解決方法,需要的可以參考一下2022-10-10
java微信開發(fā)API第二步 獲取和回復(fù)消息
這篇文章主要為大家詳細(xì)介紹了java微信開發(fā)API第二步,獲取消息和回復(fù)消息,感興趣的小伙伴們可以參考一下2016-06-06
SpringBoot項(xiàng)目從18.18M瘦身到0.18M的實(shí)現(xiàn)
本文主要介紹了SpringBoot項(xiàng)目從18.18M瘦身到0.18M的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

