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一直。