Netflix的Hystrix在對微服務降級處理實現提供兩種方式
通過添加注解@HystrixCommand方式來實現
通過繼承HystrixCommand類來實現
1. 使用@HystrixCommand注解實現服務降級
使用注解可以最小程度地侵入代碼,可以快速讓原來的功能支持服務降級,使用時僅需在要進行服務降級處理的方法上增加@HystrixCommand注解即可,并通過fallbackMethod屬性設置該方法在降級處理時所使用的方法,然后在降級方法中實現服務降級邏輯處理,需要注意:通過fallbackMethod所指定的方法要與原方法具有相同的方法簽名,否則會降級失敗。
@HystrixCommand注解說明如下:
groupKey: 設置HystrixCommand分組的名稱
commandKey: 設置HystrixCommand的名稱
threadPollKey: 設置HystrixCommand執行線程池的名稱
fallbackMethod: 設置HystrixCommand服務降級所使用的方法名稱,注意該方法需要與原方法定義在同一個類中,并且方法簽名也要一致
commandProperties: 設置HystrixCommand屬性,如:斷路器失敗百分比、斷路器時間容器大小等
ignoreException: 設置HystrixCommand執行服務降級處理時需要忽略的異常,當出現異常時不會執行服務降級處理。
observableExecutionMode: 設置HystrixCommand執行的方式
defaultFallback: 設置HystrixCommand默認的服務降級處理方法,如果同時設定了fallbackMethod,會優先使用fallbackMethod所指定的方法,需要注意的是defaultFallback該屬性所指定的方法沒有參數,需要注意返回值與原方法返回值的兼容性
2. 繼承HystrixCommand實現服務降級
除了使用注解方式來完成服務降級實現之外,Hystrix還提供了兩個對象來支持服務降級實現處理:HystrixCommand和HystrixObserableCommand,HystrixObserableCommand用于所依賴服務返回多個操作結果的時候,在實現服務降級時,如果是繼承HystrixCommand則需要實現getFallback()方法,如果是繼承HystrixObserableCommand則需要實現resumeWithFallback()方法
繼承HystrixCommand實現服務降級:
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
public class HystrixFallback extends HystrixCommand<String> {
private String name;
public HystrixFallback() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("test")));
}
public HystrixFallback(String name) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("test")));
this.name = name;
}
@Override
protected String run() throws Exception {
// 實現具體的業務處理邏輯
return null;
}
@Override
protected String getFallback() {
// 實現服務降級處理邏輯
return super.getFallback();
}
}
繼承HystrixObservableCommand實現服務降級
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import rx.Observable;
public class HystrixObervableFallback extends HystrixObservableCommand<String> {
private String name;
public HystrixObervableFallback() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("test")));
}
public HystrixObervableFallback(String name) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("test")));
this.name = name;
}
@Override
protected Observable<String> construct() {
// 實現具體的業務處理邏輯
return null;
}
@Override
protected Observable<String> resumeWithFallback() {
// 實現服務降級處理邏輯
return super.resumeWithFallback();
}
}