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

Hystrix降級-服務(wù)提供方
- 在服務(wù)提供方,引入 hystrix 依賴
- 定義降級方法
- 使用 @HystrixCommand 注解配置降級方法
- 在啟動類上開啟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;
/**
* 啟動類
*/
@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ù)超時
* 默認1s超時
*
*@HystrixCommand(fallbackMethod = "findOne_fallback")
* fallbackMethod 指定降級后的名稱
* @param id
* @return
*/
@GetMapping("/findOne/{id}")
@HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = {
//設(shè)置Hystrix的超時時間 默認1s
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})///指定降級后的方法
public Goods findOne(@PathVariable("id") int id) {
///1 造個異常
//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è)置到了 商品標題上
return goods;
}
/**
* 定義降級放啊
* 1 方法的返回值需要和原方法一樣
* 2 方法參數(shù)需要和原方法一樣
*/
public Goods findOne_fallback(int id) {
Goods goods = new Goods();
goods.setTitle("降級了~~~");
return goods;
}
}指定坐標
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
Hystrix降級-服務(wù)消費方
- feign 組件已經(jīng)集成了 hystrix 組件。
- 定義feign 調(diào)用接口實現(xiàn)類,復寫方法,即降級方法
- 在 @FeignClient 注解中使用 fallback 屬性設(shè)置降級處理類。
- 配置開啟 feign.hystrix.enabled = true
provider與Fiegin一致
application.yml修改
server:
port: 9000eureka:
instance:
hostname: localhost # 主機名
client:
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: hystrix-consumer # 設(shè)置當前應(yīng)用的名稱。將來會在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);
}
復寫方法
package com.itheima.consumer.feign;
import com.itheima.consumer.domain.Goods;
import org.springframework.stereotype.Component;
/**
* Fegin 客戶端降級處理類
* 1 定義類 實現(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 熔斷機制,用于監(jiān)控微服務(wù)調(diào)用情況,當失敗的情況達到預定的閾值(5秒失敗20次),會打開斷路器,拒絕所有請求,直到服務(wù)恢復正常為止。
- circuitBreaker.sleepWindowInMilliseconds:監(jiān)控時間
- circuitBreaker.requestVolumeThreshold:失敗次數(shù)
- circuitBreaker.errorThresholdPercentage:失敗率

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


Turbine聚合監(jiān)控
搭建監(jiān)控模塊
1. 創(chuàng)建監(jiān)控模塊
創(chuàng)建hystrix-monitor模塊,使用Turbine聚合監(jiān)控多個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>
<!--單獨熔斷監(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)建啟動類
@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、導入依賴:
<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
此處為了方便,將其配置在啟動類中。
@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、啟動類上添加注解@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;
}
}
啟動測試
1、啟動服務(wù):
- eureka-server
- hystrix-provider
- hystrix-consumer
- hystrix-monitor
2、訪問:
在瀏覽器訪問http://localhost:8769/hystrix/ 進入Hystrix Dashboard界面

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

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

到此這篇關(guān)于SpringCloud Hystrix熔斷器使用方法介紹的文章就介紹到這了,更多相關(guān)SpringCloud Hystrix熔斷器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringCloud Gateway動態(tài)路由配置詳解
- Spring?Cloud?Gateway遠程命令執(zhí)行漏洞分析(CVE-2022-22947)
- SpringSecurit鹽值加密的密碼驗證以及強密碼驗證過程
- Spring?Cloud?Alibaba實現(xiàn)服務(wù)的無損下線功能(案例講解)
- springcloud-gateway集成knife4j的示例詳解
- SpringCloud?Alibaba環(huán)境集成之nacos詳解
- Spring?Cloud?Ribbon?負載均衡使用策略示例詳解
- SpringCloud @RefreshScope刷新機制深入探究
- SpringCloud?@RefreshScope刷新機制淺析
- SpringCloud啟動失敗問題匯總
- 一文吃透Spring?Cloud?gateway自定義錯誤處理Handler
- SpringCloud Gateway路由組件詳解
- SpringCloud OpenFeign基本介紹與實現(xiàn)示例
- Spring Cloud Gateway替代zuul作為API網(wǎng)關(guān)的方法
- SpringCloud使用Feign實現(xiàn)遠程調(diào)用流程詳細介紹
- SpringCloud修改Feign日志記錄級別過程淺析
- SpringCloud開啟session共享并存儲到Redis的實現(xiàn)
- Spring?Cloud原理以及核心組件詳解
相關(guān)文章
Java 根據(jù)貸款年限對應(yīng)利率計算功能實現(xiàn)解析
這篇文章主要介紹了Java 根據(jù)貸款年限對應(yīng)利率計算功能實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-10-10
Java結(jié)合Vue項目打包并進行服務(wù)器部署
本文主要介紹了Java結(jié)合Vue項目打包并進行服務(wù)器部署,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07
深入Synchronized和java.util.concurrent.locks.Lock的區(qū)別詳解
本篇文章是對Synchronized和java.util.concurrent.locks.Lock的區(qū)別進行了詳細的分析介紹,需要的朋友參考下2013-06-06
Java 并發(fā)編程:volatile的使用及其原理解析
下面小編就為大家?guī)硪黄狫ava 并發(fā)編程:volatile的使用及其原理解析。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05

