Hystrix有隔离策略和RequestContextHolder
Hystrix有隔离策略包括:THREAD和SEMAPHORE
当隔离策略为 THREAD 时,是没办法拿到ThreadLocal中的值的。例如下面这段代码,我要使用Feign调用某个远程的方法,但是获取的(RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes())requestAttributes为Null、现在我的 feign.hystrix.enabled=true
@Configuration
@Controller
public class FeignRequestConfig {
private static Logger logger = LoggerFactory.getLogger(FeignRequestConfig.class);
@Bean
public RequestInterceptor requestInterceptor(){
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
// 现在获取的requestAttributes为null
RequestAttributes requestAttributes =
RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return;
}
}
};
return requestInterceptor;
}
}
解决方法(方案一)
requestInterceptor 之所以为null,原因就在于,Hystrix的默认隔离策略是THREAD 。而RequestContextHolder源码中,使用了两个ThreadLocal、调整Hystrix的默认隔离策略:
hystrix.command.default.execution.isolation.strategy=SEMAPHORE
注:该方案不是官方很推荐的方案,官方推荐自定义并发策略,需要自己编写一个类,让其继承
HystrixConcurrencyStrategy类,重写wrapCallable方法,【由于自定义并发策略方案以及后续带来的问题,我还没有落地实践,不敢乱写,尽请谅解、后续实践后,再补充文章】