博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
解决SpringCloud使用Feign跨服调用时header请求头中的信息丢失
阅读量:4479 次
发布时间:2019-06-08

本文共 5201 字,大约阅读时间需要 17 分钟。

在使用SpringCloud进行Feign跨服调用时header请求头中的信息会丢失,是因为Feign是不会带上当前请求的Cookie信息和头信息的,这个时候就需要重写请求拦截。

1、需要重写RequestInterceptor接口中的apply方法(前提是Feign的隔离策略为SEMAPHORE)

@Componentpublic class FeignInterceptor implements RequestInterceptor{    @Override    public void apply(RequestTemplate template) {        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();        if (attributes != null) {            HttpServletRequest request = attributes.getRequest();           //将token信息放入header中            template.header("access_token",request.getHeader("access_token"));        }    }}

注意当Feign的隔离策略为THREAD,由于当使用该隔离策略时,是没办法拿到 ThreadLocal 中的值的,但是RequestContextHolder 源码中,使用了两个ThreadLocal,因此当使用该隔离策略时是没有办法通过RequestContextHolder获取到request对象的,这时如果你还坚持使用THREAD这个隔离策略就需要自定义策略(重写THREAD隔离策略),代码如下:

/** * 自定义并发策略 * 将现有的并发策略作为新并发策略的成员变量 * 在新并发策略中,返回现有并发策略的线程池、Queue * * hystrix.command.default.execution.isolation.strategy=THREAD   Hystrix的默认隔离策略(官方推荐,当使用该隔离策略时,是没办法拿到 ThreadLocal 中的值的,但是 *                                                               RequestContextHolder 源码中,使用了两个ThreadLocal) * hystrix.command.default.execution.isolation.strategy=SEMAPHORE (将隔离策略改为SEMAPHORE 也可以解决这个问题,但是官方并不推荐这个策略,因为这个策略对网络资源消耗比较大) * * 主要是解决当 Hystrix的默认隔离策略是THREAD时,不能通过RequestContextHolder获取到request对象的问题 * * Create By yxl on 2018/5/22 */@Componentpublic class FeignConfig extends HystrixConcurrencyStrategy {    private static final Logger log = LoggerFactory.getLogger(FeignConfig.class);    private HystrixConcurrencyStrategy delegate;    public FeignConfig() {        try {            this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy();            if (this.delegate instanceof FeignConfig) {                // Welcome to singleton hell...                return;            }            HystrixCommandExecutionHook commandExecutionHook =                    HystrixPlugins.getInstance().getCommandExecutionHook();            HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();            HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();            HystrixPropertiesStrategy propertiesStrategy =                    HystrixPlugins.getInstance().getPropertiesStrategy();            this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy);            HystrixPlugins.reset();            HystrixPlugins.getInstance().registerConcurrencyStrategy(this);            HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);            HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);            HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);            HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);        } catch (Exception e) {            log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);        }    }    private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,                                                 HystrixMetricsPublisher metricsPublisher, HystrixPropertiesStrategy propertiesStrategy) {        if (log.isDebugEnabled()) {            log.debug("Current Hystrix plugins configuration is [" + "concurrencyStrategy ["                    + this.delegate + "]," + "eventNotifier [" + eventNotifier + "]," + "metricPublisher ["                    + metricsPublisher + "]," + "propertiesStrategy [" + propertiesStrategy + "]," + "]");            log.debug("Registering Sleuth Hystrix Concurrency Strategy.");        }    }    @Override    public 
Callable
wrapCallable(Callable
callable) { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); return new WrappedCallable<>(callable, requestAttributes); } @Override public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixProperty
corePoolSize, HystrixProperty
maximumPoolSize, HystrixProperty
keepAliveTime, TimeUnit unit, BlockingQueue
workQueue) { return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override public BlockingQueue
getBlockingQueue(int maxQueueSize) { return this.delegate.getBlockingQueue(maxQueueSize); } @Override public
HystrixRequestVariable
getRequestVariable(HystrixRequestVariableLifecycle
rv) { return this.delegate.getRequestVariable(rv); } static class WrappedCallable
implements Callable
{ private final Callable
target; private final RequestAttributes requestAttributes; public WrappedCallable(Callable
target, RequestAttributes requestAttributes) { this.target = target; this.requestAttributes = requestAttributes; } @Override public T call() throws Exception { try { RequestContextHolder.setRequestAttributes(requestAttributes); return target.call(); } finally { RequestContextHolder.resetRequestAttributes(); } } }}

 

转载于:https://www.cnblogs.com/Amaris-Lin/p/10654514.html

你可能感兴趣的文章
(~)按位取反符
查看>>
poj 2387 Dijkstra 模板
查看>>
求教关于ActionBar 样式问题
查看>>
hdu 5833 Zhu and 772002 ccpc网络赛 高斯消元法
查看>>
12.Linux中外接显示器分辨率不匹配的问题
查看>>
微信开发----JS-SDK接口
查看>>
微软嵌入式WEC2013产品研讨会(深圳站---2013.10.16)
查看>>
216. Combination Sum III java solutions
查看>>
sqlserver2008用sa登陆
查看>>
总是差和自由时差
查看>>
1196: [HNOI2006]公路修建问题 - BZOJ
查看>>
java 单例模式详解
查看>>
RHEL内核管理
查看>>
洛谷 3784(bzoj 4913) [SDOI2017]遗忘的集合——多项式求ln+MTT
查看>>
jQuery validation学习(1)验证只输入空格通过验证
查看>>
Sybase数据库异常紧急恢复
查看>>
抓包工具(查看协议)
查看>>
Nodejs - child_process - execFile(), exec(), spawn(), fork
查看>>
中介者模式小记【原创】
查看>>
转:Sublime Text 2 实用快捷键[Mac OS X]
查看>>