一文讀懂Spring Cloud-Hystrix
Hystrix概述
Hystrix:斷路器,容錯(cuò)管理工具,旨在通過熔斷機(jī)制控制服務(wù)和第三方庫的節(jié)點(diǎn),從而對(duì)延遲和故障提供更強(qiáng)大的容錯(cuò)能力。
hystrix可以實(shí)現(xiàn)降級(jí)和熔斷:
- 降級(jí)
調(diào)用遠(yuǎn)程服務(wù)失?。ㄥ礄C(jī)、500錯(cuò)、超時(shí)),可以降級(jí)執(zhí)行當(dāng)前服務(wù)中的一段代碼,向客戶端返回結(jié)果
快速失敗
- 熔斷
當(dāng)訪問量過大,出現(xiàn)大量失敗,可以做過熱保護(hù),斷開遠(yuǎn)程服務(wù)不再調(diào)用
限流
防止故障傳播、雪崩效應(yīng)

在微服務(wù)系統(tǒng)中,服務(wù)之間進(jìn)行依賴,避免有調(diào)用其中服務(wù)失敗,而引起其他服務(wù)大范圍宕機(jī),造成雪崩效應(yīng),hystrix熔斷可在滿足熔斷條件(默認(rèn)10秒20次以上請(qǐng)求,同時(shí)50%失敗)后執(zhí)行降級(jí)??焖贁嚅_故障服務(wù),保護(hù)其他服務(wù)不受影響。
降級(jí)
第一步:sp06添加hystrix依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
第二步:主程序添加 @EnableCircuitBreaker 啟用 hystrix 斷路器

package cn.tedu.sp06;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@EnableCircuitBreaker
@SpringBootApplication
public class Sp06RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(Sp06RibbonApplication.class, args);
}
/**
* 創(chuàng)建RestTemplate實(shí)例
* 放入spring容器
* @LoadBalanced-對(duì)RestTemplate進(jìn)行增強(qiáng),封裝RestTemplate,添加負(fù)載均衡功能
*/
@LoadBalanced
@Bean public RestTemplate restTemplate(){
//設(shè)置調(diào)用超時(shí)時(shí)間,超時(shí)后認(rèn)為調(diào)用失敗
SimpleClientHttpRequestFactory f =
new SimpleClientHttpRequestFactory();
f.setConnectTimeout(1000);//建立連接等待時(shí)間
f.setReadTimeout(1000);//連接建立后,發(fā)送請(qǐng)求后,等待接收響應(yīng)的時(shí)間
return new RestTemplate(f);
}
}
第三步:RibbonController 中添加降級(jí)方法
- 為每個(gè)方法添加降級(jí)方法,例如
getItems()添加降級(jí)方法getItemsFB() - 添加
@HystrixCommand注解,指定降級(jí)方法名
package cn.tedu.sp06.controller;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@Slf4j
public class RibbonController {
@Autowired
private RestTemplate rt;
@GetMapping("/item-service/{orderId}")
@HystrixCommand(fallbackMethod = "getItemsFB") //指定降級(jí)方法的方法名
public JsonResult<List<Item>> getItems(@PathVariable String orderId){
return rt.getForObject("http://item-service/{1}", JsonResult.class,orderId);
}
@PostMapping("/item-service/decreaseNumber")
@HystrixCommand(fallbackMethod = "decreaseNumberFB") //指定降級(jí)方法的方法名
public JsonResult<?> decreaseNumber(@PathVariable List<Item> items){
return rt.postForObject("http://item-service/decreaseNumber",items, JsonResult.class);
}
@GetMapping("/user-service/{userId}")
@HystrixCommand(fallbackMethod = "getUserFB") //指定降級(jí)方法的方法名
public JsonResult<User> getUser(@PathVariable Integer userId) {
return rt.getForObject("http://user-service/{1}", JsonResult.class, userId);
}
@GetMapping("/user-service/{userId}/score")
@HystrixCommand(fallbackMethod = "addScoreFB") //指定降級(jí)方法的方法名
public JsonResult addScore(
@PathVariable Integer userId, Integer score) {
return rt.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class, userId, score);
}
@GetMapping("/order-service/{orderId}")
@HystrixCommand(fallbackMethod = "getOrderFB") //指定降級(jí)方法的方法名
public JsonResult<Order> getOrder(@PathVariable String orderId) {
return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId);
}
@GetMapping("/order-service")
@HystrixCommand(fallbackMethod = "addOrderFB") //指定降級(jí)方法的方法名
public JsonResult addOrder() {
return rt.getForObject("http://order-service/", JsonResult.class);
}
//降級(jí)方法的參數(shù)和返回值,需要和原始方法一致,方法名任意
public JsonResult<List<Item>> getItemsFB(String orderId) {
return JsonResult.err("獲取訂單商品列表失敗");
}
public JsonResult decreaseNumberFB(List<Item> items) {
return JsonResult.err("更新商品庫存失敗");
}
public JsonResult<User> getUserFB(Integer userId) {
return JsonResult.err("獲取用戶信息失敗");
}
public JsonResult addScoreFB(Integer userId, Integer score) {
return JsonResult.err("增加用戶積分失敗");
}
public JsonResult<Order> getOrderFB(String orderId) {
return JsonResult.err("獲取訂單失敗");
}
public JsonResult addOrderFB() {
return JsonResult.err("添加訂單失敗");
}
}
第四步:?jiǎn)?dòng)eureka、item和hystrix服務(wù)器進(jìn)行測(cè)試
http://localhost:3001/item-service/35

hystrix超時(shí)設(shè)置:
超時(shí)時(shí)間設(shè)置應(yīng)該超過ribbon重試時(shí)間,否則重試失效。
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix等待超時(shí)后, 會(huì)執(zhí)行降級(jí)代碼, 快速向客戶端返回降級(jí)結(jié)果, 默認(rèn)超時(shí)時(shí)間是1000毫秒。
可在yml中設(shè)置超時(shí)時(shí)間:
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000
熔斷
主程序添加 @EnableCircuitBreaker 啟用 hystrix 斷路器,熔斷自動(dòng)打開。

Hystrix故障監(jiān)控-Hystrix Dashboard斷路器儀表盤
Hystrix使用springboot提供的actuator健康管理,監(jiān)控各個(gè)端點(diǎn)。

actuator中的hystrix.stream可以監(jiān)控hystrix斷路器各端點(diǎn)日志。

第一步:sp06的pom中添加actuator依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <version>2.4.0</version> </dependency>
第二步:在yml中配置健康監(jiān)控的內(nèi)容
# "*"暴露所有監(jiān)控端點(diǎn)
management:
endpoints:
web:
exposure:
include: "*"
第三步:測(cè)試actuator健康監(jiān)控
http://localhost:3001/actuator/ 搭建Hystrix Dashboard儀表盤:
儀表盤項(xiàng)目是一個(gè)完全獨(dú)立的項(xiàng)目。
第一步:創(chuàng)建springboot項(xiàng)目sp08-htstrix-dashboard

第二步:添加hystrix dashboard依賴

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId> </dependency>
第三步:主程序上添加@EnableHystrixDashboard注解
package cn.tedu.sp08;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@EnableHystrixDashboard
@SpringBootApplication
public class Sp08HystrixDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(Sp08HystrixDashboardApplication.class, args);
}
}
第四步:配置允許給那些服務(wù)器開啟權(quán)限
hystrix: dashboard: proxy-stream-allow-list: localhost
第五步:監(jiān)控查看
http://localhost:4001/hystrix/

第六步:查看hystrix stream監(jiān)控?cái)?shù)據(jù)端點(diǎn)
輸入hystrix監(jiān)控地址

訪問item/user/order服務(wù)器,查看儀表盤。

第六步:使用ab進(jìn)行并發(fā)訪問測(cè)試
使用 apache 的并發(fā)訪問測(cè)試工具 ab進(jìn)行訪問測(cè)試。
打開ab工具/bin文件目錄--cmd--輸入命令:
ab -n 20000 -c 50 http://localhost:3001/item-service/35
并發(fā)50,發(fā)送20000個(gè)請(qǐng)求,查看儀表盤。
到此這篇關(guān)于一文讀懂Spring Cloud-Hystrix的文章就介紹到這了,更多相關(guān)Spring Cloud Hystrix內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解在Spring中如何使用AspectJ來實(shí)現(xiàn)AOP
這篇文章主要介紹了詳解在Spring中如何使用AspectJ來實(shí)現(xiàn)AOP,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-06-06
linux的shell命令檢測(cè)某個(gè)java程序是否執(zhí)行
ps -ef |grep java|grep2016-04-04
spring根據(jù)controller中接收請(qǐng)求參數(shù)不同走不同service的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于spring實(shí)現(xiàn)根據(jù)controller中接收請(qǐng)求參數(shù)不同走不同service的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2018-11-11
springboot項(xiàng)目開啟https協(xié)議的項(xiàng)目實(shí)現(xiàn)
本文主要介紹了springboot項(xiàng)目開啟https協(xié)議的項(xiàng)目實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
利用Java實(shí)現(xiàn)簡(jiǎn)單的猜數(shù)字小游戲
這篇文章主要為大家詳細(xì)介紹了如何利用java語言實(shí)現(xiàn)猜數(shù)字小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
springBoot詳細(xì)講解使用mybaties案例
MyBatis本是apache的一個(gè)開源項(xiàng)目iBatis,2010年這個(gè)項(xiàng)目由apache software foundation遷移到了google code,并且改名為MyBatis。2013年11月遷移到Github。iBATIS一詞來源于“internet”和“abatis”的組合,是一個(gè)基于Java的持久層框架2022-05-05
淺談Java由于不當(dāng)?shù)膱?zhí)行順序?qū)е碌乃梨i
為了保證線程的安全,我們引入了加鎖機(jī)制,但是如果不加限制的使用加鎖,就有可能會(huì)導(dǎo)致順序死鎖(Lock-Ordering Deadlock)。本文將會(huì)討論一下順序死鎖的問題。2021-06-06
Java實(shí)現(xiàn)的爬蟲抓取圖片并保存操作示例
這篇文章主要介紹了Java實(shí)現(xiàn)的爬蟲抓取圖片并保存操作,涉及Java針對(duì)頁面URL訪問、獲取、字符串匹配、文件下載等相關(guān)操作技巧,需要的朋友可以參考下2018-08-08

