feign集成hystrix获取不到RequestContextHolder.currentRequestAttributes
1、问题描述
SpringBoot项目中使用到了feign作为Cloud平台内部微服务之间的接口调用,内部组件之间调用过程中,需要在RequestTemplate中添加请求头header鉴权等信息,而feign在开启了httpclient和hystrix支持后,发现RequestContextHolder.currentRequestAttributes()抛No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.异常。
yml引入feign、hystrix配置如下:
feign:
httpclient:
enabled: true
hystrix:
enabled: true
compression: #开启GZIP
request:
enabled: true
response:
enabled: true
hystrix:
threadpool:
default:
coreSize: 20 # 设置线程池大小为20
metrics:
enabled: true
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 60000
timeout:
enabled: false
2、问题分析
hystrix使用多线程管理请求连接池,从主线程到发送基于hystrix的feign请求线程已不在同一个线程内,而RequestContextHolder是基于ThreadLocal实现的,这就使得线程之间数据断链,需要通过线程之间的数据传递使得ThreadLocal中存储的currentRequestAttributes接上。hystrix强大在于是支持此扩展操作的。
3、通过HystrixConcurrencyStrategy自定义策略,解决线程间的数据传递
废话不多说,直接上代码:
package com.xx.xx.app.config;
import java.util.concurrent.Callable;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
/**
* @author zhouyuhhu
* @date 2019/12/26
*/
public class RequestContextHystrixConcurrencyStrategy <