Springboot feign 传递request信息

基础实现

requestInterceptor 实现类中添加信息

public class NativeFeignConf {
    @Bean
    public RequestInterceptor getRequestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
                HttpServletRequest req=servletRequestAttributes.getRequest();
                Map<String,Collection<String>> headerMap=new HashMap();
                //获取你需要传递的头信息
                String myHeaderVal=req.getHeader("myHeader");
                headerMap.put("myHeader",Arrays.asList(myHeaderVal));
                //feign请求时,便可携带上该信息
                requestTempalte.headers(headerMap);
    }
}

feign加入该config

@FeignClient(
    value="target-service",
    configuration=NativeFeignConf.class //加入该配置
)
public interface MyFeign(){
    ...
} 

开启 Hystrix 的情况下

开启hystrix后,feign请求,会运行在hystrix管理的另一线程下。

所以RequestContextHolder.currentRequestAttributes()无法获取值。

解决方法:

创建一个自定义的hystrix 线程策略, 将servletRequestAttributes传入新线程中,并赋给RequestContextHolder:

public class MyHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy{
    @Override
    public <T> Callable<T> wrapCallable(Callable<T> callable){
        ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return new Callable<T>() {
            @Override
            public T call() throws Exception {
                try {
                    if (null != servletRequestAttributes) {
                        RequestContextHolder.setRequestAttributes(servletRequestAttributes);
                    }
                    return callable.call();
                }finally {
                    RequestContextHolder.resetRequestAttributes();
                }
            }
        };
    }
}

注册该策略

@Configuration
public class HystrixConfig{
    @PostConstruct
    public void init(){
        HystrixPlugins.getInstance().registerConcurrencyStrategy(
            new MyHystrixConcurrencyStrategy()
        )
    }
}

结束。

文章来自:https://www.cnblogs.com/ztwBlog/p/12302133.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3