使用feign服务调用添加Header参数


Posted in Java/Android onJune 23, 2021

feign添加Header参数

@Configuration
public class FeignConfiguration implements RequestInterceptor {	
	private static final Logger logger = LoggerFactory.getLogger(FeignConfiguration.class);
	
	@Override
	public void apply(RequestTemplate template) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if(null != attributes) {
			HttpServletRequest request = attributes.getRequest();
	        String token = request.getHeader("token");
	        template.header("token", token);
		}
        logger.info("feign interceptor header:{}",template);
	}
}

Feign设置Header头部,@Headers无效

在使用FeignClient调用外部接口的时候,需要在请求头部添加header的参数,用于请求的认证。在查找Feign文档中提供了@Headers注解,该注解可以完成头部的添加。但是却没有生效

@FeignClient(name="name",url = "127.0.0.1:8090/test",path = "/")
public interface IUserService { 
    @RequestMapping(value = "getUserPage",method = RequestMethod.POST)
    @Headers(value={"ContentType=application/x-www-form-urlencoded","Inner_token=PXH0dP5I8qQ8UbFPpzm67cQkm7j8tWT2Kwn6J6SXYkfp2kMo/lSqHQ=="})
    public Map<String,Object> getUserPage(User user);
}

在服务端获取不到Inner_token的头部参数。得到的结果是null

于是开启feign的日志

第一步:定义feign的日志配置文件类

@Configuration
public class FeignConfig { 
    @Bean
    Logger.Level feignLevel(){
        return Logger.Level.FULL;
    }
}

第二步:在调用的FeignClien客户端注解上指定该日志级别配置文件

@FeignClient(name="name",url = "127.0.0.1:8090/test",path = "/",configuration = FeignConfig.class)
public interface IUserService { 
    @RequestMapping(value = "getUserPage",method = RequestMethod.POST)
    @Headers(value={"ContentType=application/x-www-form-urlencoded","Inner_token=PXH0dP5I8qQ8UbFPpzm67cQkm7j8tWT2Kwn6J6SXYkfp2kMo/lSqHQ=="})
    public Map<String,Object> getUserPage(User user);
}

第三步:配置yml文件,指定该feignclient的配置路径和日志级别

logging:
  level:
    demo.IUserService: debug

重启,并发起请求

2019-09-27 10:46:01.662 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] ---> POST http://127.0.0.1:8090/test/getUserPage HTTP/1.1
2019-09-27 10:46:01.663 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] Content-Type: application/json;charset=UTF-8
2019-09-27 10:46:01.663 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] Content-Length: 53
2019-09-27 10:46:01.663 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage]
2019-09-27 10:46:01.663 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] {"id":0,"tableName":"feignTable","page":10,"size":10}
2019-09-27 10:46:01.663 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] ---> END HTTP (53-byte body)
2019-09-27 10:46:01.684 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] <--- HTTP/1.1 200 (21ms)
2019-09-27 10:46:01.684 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] content-type: application/json;charset=UTF-8
2019-09-27 10:46:01.685 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] date: Fri, 27 Sep 2019 02:46:01 GMT
2019-09-27 10:46:01.685 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] transfer-encoding: chunked
2019-09-27 10:46:01.685 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] x-application-context: HelloServer:8090
2019-09-27 10:46:01.685 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage]
2019-09-27 10:46:01.689 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] {"success":true,"rows":[{"id":10111,"tableName":"hbaseTable","page":1,"size":20},{"id":10112,"tableName":"hbaseTable","page":1,"size":20},{"id":10113,"tableName":"hbaseTable","page":1,"size":20},{"id":10114,"tableName":"hbaseTable","page":1,"size":20},{"id":10115,"tableName":"hbaseTable","page":1,"size":20},{"id":10116,"tableName":"hbaseTable","page":1,"size":20},{"id":10117,"tableName":"hbaseTable","page":1,"size":20},{"id":10118,"tableName":"hbaseTable","page":1,"size":20},{"id":10119,"tableName":"hbaseTable","page":1,"size":20},{"id":10120,"tableName":"hbaseTable","page":1,"size":20}]}
2019-09-27 10:46:01.689 DEBUG 15200 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] <--- END HTTP (595-byte body)

在日志中发现,header中没有被加上我之前设置的参数。说明该注解没有生效

于是debug调试

通过debug我发现feign会先将请求参数构建成Request对象,request信息如下:

使用feign服务调用添加Header参数

从图中可看到,该Request实例的headers属性为空,而Request又是根据RequestTemplate模板对象生成的,RequestTemplate实例信息如下:

使用feign服务调用添加Header参数

到这里可以看出,问题是出在RequestTemplate的构建构成中,于是我就去跟踪RequestTemplate构建的代码,发现RequestTemplate是根据MethodMetadata构建而成,而MethodMetadata就是对方法配置的抽象。

RequestTemplate template = resolve(argv, mutable, varBuilder);
      if (metadata.queryMapIndex() != null) {
        // add query map parameters after initial resolve so that they take
        // precedence over any predefined values
        template = addQueryMapQueryParameters(argv, template);
      }
 
      if (metadata.headerMapIndex() != null) {
        template = addHeaderMapHeaders(argv, template);
      }

从上述代码可以看到,header的设置是由metadata的headerMapIndex 属性决定的,那么,设置headerMapIndex的位置,必然就和Header的解析相关,于是通过查看方法引用,我找到了下面的代码:

private void parseHeaders(MethodMetadata md, Method method,
            RequestMapping annotation) {
        // TODO: only supports one header value per key
        if (annotation.headers() != null && annotation.headers().length > 0) {
            for (String header : annotation.headers()) {
                int index = header.indexOf('=');
                if (!header.contains("!=") && index >= 0) {
                    md.template().header(resolve(header.substring(0, index)),
                        resolve(header.substring(index + 1).trim()));
                }
            }
        }
    }

从代码中我们可以清晰的看到,解析过程中是从@RequestMapping或其派生注解的header属性中解析Header的,并且Header的key和value需要用“=”进行分割。

于是我修改成下面的形式,问题就解决了:

@FeignClient(name="name",url = "127.0.0.1:8090/test",path = "/",configuration = FeignConfig.class)
public interface IUserService {
 
    @RequestMapping(value = "getUserPage",method = RequestMethod.POST,headers = {"ContentType=application/x-www-form-urlencoded","Inner_token=PXH0dP5I8qQ8UbFPpzm67cQkm7j8tWT2Kwn6J6SXYkfp2kMo/lSqHQ=="})
    @Headers(value={"ContentType=application/x-www-form-urlencoded","Inner_token=PXH0dP5I8qQ8UbFPpzm67cQkm7j8tWT2Kwn6J6SXYkfp2kMo/lSqHQ=="})
    public Map<String,Object> getUserPage(User user);
}

查看请求日志

2019-09-27 11:10:29.975 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] ---> POST http://127.0.0.1:8090/test/getUserPage HTTP/1.1
2019-09-27 11:10:29.976 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] ContentType: application/x-www-form-urlencoded
2019-09-27 11:10:29.976 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] Inner_token: PXH0dP5I8qQ8UbFPpzm67cQkm7j8tWT2Kwn6J6SXYkfp2kMo/lSqHQ==
2019-09-27 11:10:29.976 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] Content-Type: application/json;charset=UTF-8
2019-09-27 11:10:29.976 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] Content-Length: 53
2019-09-27 11:10:29.976 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage]
2019-09-27 11:10:29.976 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] {"id":0,"tableName":"feignTable","page":10,"size":10}
2019-09-27 11:10:29.976 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] ---> END HTTP (53-byte body)
2019-09-27 11:10:29.992 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] <--- HTTP/1.1 200 (16ms)
2019-09-27 11:10:29.993 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] content-type: application/json;charset=UTF-8
2019-09-27 11:10:29.993 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] date: Fri, 27 Sep 2019 03:10:29 GMT
2019-09-27 11:10:29.993 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] transfer-encoding: chunked
2019-09-27 11:10:29.993 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] x-application-context: HelloServer:8090
2019-09-27 11:10:29.993 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage]
2019-09-27 11:10:29.995 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] {"success":true,"rows":[{"id":10141,"tableName":"hbaseTable","page":1,"size":20},{"id":10142,"tableName":"hbaseTable","page":1,"size":20},{"id":10143,"tableName":"hbaseTable","page":1,"size":20},{"id":10144,"tableName":"hbaseTable","page":1,"size":20},{"id":10145,"tableName":"hbaseTable","page":1,"size":20},{"id":10146,"tableName":"hbaseTable","page":1,"size":20},{"id":10147,"tableName":"hbaseTable","page":1,"size":20},{"id":10148,"tableName":"hbaseTable","page":1,"size":20},{"id":10149,"tableName":"hbaseTable","page":1,"size":20},{"id":10150,"tableName":"hbaseTable","page":1,"size":20}]}
2019-09-27 11:10:29.995 DEBUG 8604 --- [ hystrix-name-1] demo.IUserService : [IUserService#getUserPage] <--- END HTTP (595-byte body)

请求中header已经被成功添加~

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木~

Java/Android 相关文章推荐
解析Java中的static关键字
Jun 14 Java/Android
详解SpringBoot异常处理流程及原理
Jun 21 Java/Android
HashMap实现保存两个key相同的数据
Jun 30 Java/Android
解决MultipartFile.transferTo(dest) 报FileNotFoundExcep的问题
Jul 01 Java/Android
Spring Boot 排除某个类加载注入IOC的操作
Aug 02 Java/Android
MyBatis-Plus 批量插入数据的操作方法
Sep 25 Java/Android
关于@OnetoMany关系映射的排序问题,使用注解@OrderBy
Dec 06 Java/Android
JavaCV实现照片马赛克效果
Jan 22 Java/Android
解决persistence.xml配置文件修改存放路径的问题
Feb 24 Java/Android
java objectUtils 使用可能会出现的问题
Feb 28 Java/Android
Java 异步任务计算FutureTask
Apr 28 Java/Android
mybatis 获取更新记录的id
May 20 Java/Android
详解Java实现数据结构之并查集
解决SpringCloud Feign传对象参数调用失败的问题
Jun 23 #Java/Android
详解Java实现设计模式之责任链模式
Jun 23 #Java/Android
Spring boot应用启动后首次访问很慢的解决方案
Java并发编程之详解CyclicBarrier线程同步
如何解决springcloud feign 首次调用100%失败的问题
分析设计模式之模板方法Java实现
You might like
PHP新手上路(四)
2006/10/09 PHP
php语言流程控制中的主动与被动
2012/11/05 PHP
深入解析phpCB批量转换的代码示例
2013/06/27 PHP
PHP实现的简单缓存类
2015/07/29 PHP
PHP生成条形码大揭秘
2015/09/24 PHP
php 问卷调查结果统计
2015/10/08 PHP
PHP验证码类ValidateCode解析
2017/01/07 PHP
基于jquery实现的图片在各种分辨率下未知的容器内上下左右居中
2014/05/11 Javascript
JavaScript使用cookie实现记住账号密码功能
2015/04/27 Javascript
JavaScript实现简单的数字倒计时
2015/05/15 Javascript
使用bootstrap validator的remote验证代码经验分享(推荐)
2016/09/21 Javascript
js从输入框读取内容,比较两个数字的大小方法
2017/03/13 Javascript
js 用于检测类数组对象的函数方法
2017/05/02 Javascript
vue2中的keep-alive使用总结及注意事项
2017/12/21 Javascript
对vux点击事件的优化详解
2018/08/28 Javascript
在小程序/mpvue中使用flyio发起网络请求的方法
2018/09/13 Javascript
vue强制刷新组件的方法示例
2019/02/28 Javascript
详解async/await 异步应用的常用场景
2019/05/13 Javascript
Vue如何实现变量表达式选择器
2021/02/18 Vue.js
[02:34]DOTA2亚洲邀请赛 BG战队出场宣传片
2015/03/09 DOTA
解决python nohup linux 后台运行输出的问题
2018/05/11 Python
Python算法的时间复杂度和空间复杂度(实例解析)
2019/11/19 Python
智利最大的网上商店:Linio智利
2016/11/24 全球购物
StubHub新加坡:购买和出售全球活动门票
2017/03/10 全球购物
澳大利亚最大的百货公司:Myer
2018/12/21 全球购物
美国花园雕像和家居装饰网上商店:Design Toscano
2019/03/09 全球购物
小学教师国培感言
2014/02/08 职场文书
党建工作先进材料
2014/05/02 职场文书
优秀教师感人事迹材料
2014/05/04 职场文书
合同意向书范本
2014/07/30 职场文书
村主任群众路线教育实践活动个人对照检查材料思想汇报
2014/10/01 职场文书
务工证明怎么写
2015/06/18 职场文书
PHP解决高并发问题
2021/04/01 PHP
java调用Restful接口的三种方法
2021/08/23 Java/Android
人工智能深度学习OpenAI baselines的使用方法
2022/05/20 Python
Python如何利用pandas读取csv数据并绘图
2022/07/07 Python