在使用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. 蓝牙App漏洞系列分析之三CVE-2017-0645

    蓝牙App漏洞系列分析之三CVE-2017-0645 0x01 漏洞简介 Android 6月的安全公告,同时还修复了我们发现的一个蓝牙 App 提权中危漏洞,该漏洞允许手机本地无权限的恶意程序构造一 ...

  2. vue 设置全局变量、指定请求的 baseurl

    一. 基本环境前端vue:2.5.6axios:0.18使用vue脚手架构建项目.参照:webstorm搭建vue项目后台ssm框架前后端数据采用json格式传输二. 前端配置axios配置1.安装: ...

  3. Jmeter最佳录制工具BlazeMeter

    简介 在做接口测试时,开发会提供接口文档作为测试脚本编写的依据,但接口文档往往有一些局限性: 接口文档本身可能有编写错误 接口文档可以针对单个字段的取值和含义做描述,但多个字段的组合作用很难通过文字做 ...

  4. Summer training #3

    A:给一个包含字母 加号 括号的序列 要求你删除多余的括号然后输出 (待改) #include <bits/stdc++.h> #include <cstring> #incl ...

  5. 关于注解-Hebernate与JPA(java persistence api)

    The JPA spec. defines the JPA annotation in the javax.persistence package. Hibernate not only implem ...

  6. git 学习使用记录

    一.一个小时学会git:https://www.cnblogs.com/best/p/7474442.html 二.fetch fatal: Refusing to fetch into curren ...

  7. mybatis中#{}和${}的区别(转载)

    原文地址:http://www.cnblogs.com/baizhanshi/p/5778692.html 1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号.如:order by ...

  8. 如何判断元素是否在可视区域ViewPort

    个性签名: 生如夏花,逝如冬雪:人生如此,何悔何怨. 前言: 经常需要计算元素的大小或者所在页面的位置,offsetWidth,clientWidth,scrollWidth,scrollTop这几个 ...

  9. nginx缓冲区,跳转,超时

    缓冲区 nginx服务器向后台转发请求的时候, 往往只收到一下部分请求头的信息,缓冲区的意义在于尽可能多的保存请求信息. 语法配置 proxy _buffering打开后---设置为on,浏览器里面将 ...

  10. File上次文件找不到文件相对绝对路径

    我的问题是因为文件的相对绝对路径上面有中午字符,把上面的中午字符全改为英文或者数字加特殊字符形式都可以