Feign開啓HyStrix後如何配置線程隔離及熔斷策略

Feign集成Hystrix默認是關閉Hystrix的,只有在配置文件中設置feign.hystrix.enabled=true纔會開啓Hystrix。

開啓Hystrix後feign之間的方法調用就會默認啓動新的線程執行和主程序不在一個線程中,因此如果上下文中存在ThreadLocal變量,在該方法中就失效了。因此一般可以通過設置CommandProperties註解屬性,設置線程就可以了。

在和Feign整合後,用戶無法配置Feign的ComandProperties,但是可以通過配置Bean的形式配置。

@Configuration
public class FeignSupportConfig {
	@Bean
	public SetterFactory setterFactory(){
		SetterFactory setterFactory =new SetterFactory() {
			@Override
			public HystrixCommand.Setter create(Target<?> target, Method method) {

				String groupKey = target.name();
				String commandKey = Feign.configKey(target.type(), method);

				HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
						//設置統計指標60秒爲一個時間窗口
						.withMetricsRollingStatisticalWindowInMilliseconds(1000 * 60)
						//超過80%失敗率
						.withCircuitBreakerErrorThresholdPercentage(80)
						//操作5個開啓短路器
						.withCircuitBreakerRequestVolumeThreshold(5)
						//設置線程隔離
						.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
						//設置斷路器的開啓時間爲60秒
						.withCircuitBreakerSleepWindowInMilliseconds(1000 * 60);

				return HystrixCommand.Setter
						.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
						.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
						.andCommandPropertiesDefaults(setter);
			}
		};
		return setterFactory;
	}

}

然後在@FeignClient中引入該配置

@FeignClient(name = "USER-SERVICE", configuration = FeignSupportConfig.class) //name爲服務名

至此,方法調用將會和主線程ID一直。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章