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

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

@Component
public 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
*/
@Component
public 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 <T> Callable<T> wrapCallable(Callable<T> callable) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return new WrappedCallable<>(callable, requestAttributes);
} @Override
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize,
HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime,
unit, workQueue);
} @Override
public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
return this.delegate.getBlockingQueue(maxQueueSize);
} @Override
public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
return this.delegate.getRequestVariable(rv);
} static class WrappedCallable<T> implements Callable<T> {
private final Callable<T> target;
private final RequestAttributes requestAttributes; public WrappedCallable(Callable<T> 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();
}
}
}
}

解决SpringCloud使用Feign跨服调用时header请求头中的信息丢失的更多相关文章

  1. SpringCloud之Feign声明式调用原理及配置

    1 什么是Feign Feign是一种声明式.模板化的HTTP客户端(仅在Application Client中使用).声明式调用是指,就像调用本地方法一样调用远程方法,无需感知操作远程http请求. ...

  2. SpringCloud系列——Feign 服务调用

    前言 前面我们已经实现了服务的注册与发现(请戳:SpringCloud系列——Eureka 服务注册与发现),并且在注册中心注册了一个服务myspringboot,本文记录多个服务之间使用Feign调 ...

  3. SpringCloud Netflix Feign

    调用其它机器上的服务(远程调用)有2种技术:REST.RPC. REST 注入RestTempalte,服务提供者的url要写成RESTful风格,在url中传递参数. 如果参数很多,url会有一长串 ...

  4. 快速解决Canvas.toDataURL 图片跨域的问题

    出现Canvas.toDataURL 图片跨域问题怎么解决呢?下面小编就为大家带来一篇Canvas.toDataURL 图片跨域问题的快速解决方法.一起跟随小编过来看看吧 如题,在将页面的图片地址进行 ...

  5. 解决Canvas.toDataURL 图片跨域问题

    如题,在将页面的图片地址进行本地输出时(Html2Canvas.js),因不同源存在跨域问题,会出现toDataURL访问权限问题: [Redirect at origin 'http://sub1. ...

  6. ajax请求头加Token时发生的跨域(CORS)请求问题

    首先描述下问题:需求是在请求头中加入token,我在ajax请求数据时添加了请求头‘Authorization’字段,并添加了响应的token值,在请求数据的时候浏览器报错如下: Request he ...

  7. Feign 自定义编码器、解码器和客户端,Feign 转发请求头(header参数)、Feign输出Info级别日志

    Feign 的编码器.解码器和客户端都是支持自定义扩展,可以对请求以及结果和发起请求的过程进行自定义实现,Feign 默认支持 JSON 格式的编码器和解码器,如果希望支持其他的或者自定义格式就需要编 ...

  8. 【跨域】SpringBoot跨域,拦截器中,第一次获取的请求头为NULL,发送两次请求的处理方式

    背景: 在做前后端分离时,牵扯到跨域,但是已经设置了跨域 前端设置了允许携带Cookie axios.defaults.withCredentials = true; 后端也配置了跨域 浏览器端查看发 ...

  9. SpringCloud设定Feign底层实现

    1. 概述 版本: spring-boot:  1.5.9.RELEASE spring-cloud: Dalston.SR5 在默认情况下 spring cloud feign在进行各个子服务之间的 ...

随机推荐

  1. NORDIC 修改MTU

    https://www.cnblogs.com/jiangjiu/p/10063556.html 注意要修改RAM起始地址,因为MTU增大了

  2. sql 脚本过大

    先把sql脚本文件中的创建部分  剪切 出来执行,创建一个数据库 然后执行cmd命令 sqlcmd   -S    CAOHONGWEI   -U   sa   -P   p@ss!123   -d  ...

  3. hive单机部署

    hadoop,hbase,zookeeper安装好了,现在来安装hive hadoop 版本:2.8.4 hbase 版本:2.1.3 hive 版本:2.3.4 zookeeper 版本:3.4.1 ...

  4. 使用google身份验证器实现动态口令验证

    最近有用户反应我们现有的短信+邮件验证,不安全及短信条数限制和邮件收验证码比较慢的问题,希望我们 也能做一个类似银行动态口令的验证方式.经过对可行性的分析及慎重考虑,可以实现一个这样的功能. 怎么实现 ...

  5. Linux( Ubantu ) 的简单使用

    1.Linux常用的快捷键 Ctrl + Alt+ T --打开终端 Ctrl + Shift + C --复制 Ctrl + Shift + V --粘贴 Ctrl + Shift + A --光标 ...

  6. BZOJ 3626 [LNOI2014]LCA 树剖+(离线+线段树 // 在线+主席树)

    BZOJ 4012 [HNOI2015]开店 的弱化版,离线了,而且没有边权(长度). 两种做法 1 树剖+离线+线段树 这道题求的是一个点zzz与[l,r][l,r][l,r]内所有点的lcalca ...

  7. HDU-3336-Count the string(扩展KMP)

    链接: https://vjudge.net/problem/HDU-3336 题意: It is well known that AekdyCoin is good at string proble ...

  8. 漫话:什么是 https ?这应该是全网把 https 讲的最好的一篇文章了

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/m0_37907797/article/d ...

  9. IE8下,去除iframe的边框

    iframe边框通过css设定在FF下正常在ie下却还存在边框,设置frameborder="0"和border="0"可以去掉讨厌的iframe边框 < ...

  10. 交换机配置——三层交换机实现VLAN间通信

    一.实验目的::用三层交换机让同一vlan的主机能通信,不同vlan的主机也能通信 二.拓扑图如下 三.具体步骤如下:. 先给每台主机和服务器配置ip地址和网关 例: (1)S1三层交换机配置: Sw ...