一、前言
Hystrix是一個用于處理分布式系統的延遲和容錯的開源庫,在分布式系統里,許多依賴不可避免的會呼叫失敗,比如超時,例外等,Hystrix能夠保證在一個依賴出現問題的情況下,不會導致整體服務失敗,避免級聯故障,以提高分布式系統的彈性,
? “斷路器”本身是一種開關設定,當某個服務單元發生故障之后,通過斷路器的故障監控(類似熔斷保險絲),向呼叫方法回傳一個服務預期的,可處理的備選回應(FallBack),而不是長時間的等待或者拋出呼叫方法無法處理的例外,這樣就可以保證了服務呼叫方的執行緒不會被長時間,不必要的占用,從而避免了故障在分布式系統中的蔓延,乃至雪崩,
? 那么Hystrix能夠做一些什么呢?
- 服務降級,服務熔斷,服務限流,實時監控
以及一些分流,依賴分離之類等等,這里我們將用簡單的介紹服務熔斷和降級,并用代碼簡單演示一下,
當某個微服務不可用或者回應實踐太長時,會進行服務的降級,進而熔斷該節點微服務的呼叫,快速回傳錯誤的回應資訊,當檢測到該節點微服務呼叫回應正常后恢復呼叫鏈路,在SpringCloud框架里熔斷機制通過Hystrix實作,Hystrix會監控微服務間呼叫的狀況,當失敗的呼叫到一定的閾值,預設是5秒內20次呼叫失敗就會啟動熔斷機制,
二、服務降級(HystrixCommand)
用@HystrixCommand fallbackMethod的方式不是很好,因為和業務代碼耦合度太高,所有方法都在一個類,不利于后期維護 ,建議使用 fegin+Hystrix 整合 方式
1、匯入依賴
實作方式如下,實際請結合業務邏輯進行使用,首先匯入依賴
<!--hystrix依賴,主要是用 @HystrixCommand -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、加入注解
然后我們需要在啟動類加入 @EnableCircuitBreaker 注解
@SpringBootApplication
@EnableCircuitBreaker
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
3、服務提供介面實作,添加降級處理方法
服務降級方法,方法簽名(引數+回傳值) 需要同原方法一致,方法名不同即可,接下來我們在 在外層 api controller中可使用 @HystrixCommand(fallbackMethod = "saveOrderFail") 進行降級方法的配置
@RequestMapping("save")
@HystrixCommand(fallbackMethod = "saveOrderFail")
public Object save(@RequestParam("user_id") int userId, @RequestParam("product_id") int productId) {
Map<String, Object> data = new HashMap<>();
data.put("code", 0);
data.put("data", productOrderService.save(userId, productId));
return data;
}
//注意,方法簽名一定要要和api方法一致
private Object saveOrderFail(int userId, int productId) {
return "服務熔斷";
}
三、服務降級(fegin+Hystrix)
1、application.yml 配置,消費端添加配置 feign.hystrix.enabled=true
feign:
hystrix:
enabled: true
2、啟動類,添加 @EnableCircuitBreaker 注解
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
3、新建 fallback 降級處理方法類 并實作 feignClient 介面 的方法
/**
* 針對商品服務,錯降級處理
*/
@Component
public class ProductClientFallback implements ProductClient {
@Override
public String findById(int id) {
System.out.println("feign 呼叫product-service findbyid 例外");
return null;
}
}
四、超時時間調整
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 4000
參考文獻
https://blog.csdn.net/lzb348110175/article/details/107295017
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/152666.html
標籤:其他
