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

 更新时间:2021年06月23日 16:40:06   作者:精英丶阿琦  
这篇文章主要介绍了使用feign服务调用添加Header参数的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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信息如下:

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

到这里可以看出,问题是出在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已经被成功添加~

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家~

相关文章

  • springboot集成shiro自定义登陆过滤器方法

    springboot集成shiro自定义登陆过滤器方法

    这篇文章主要介绍了springboot集成shiro自定义登陆过滤器方法,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-08-08
  • spring注入在有常量的情况下使用@AllArgsConstructor操作

    spring注入在有常量的情况下使用@AllArgsConstructor操作

    这篇文章主要介绍了spring注入在有常量的情况下使用@AllArgsConstructor操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • Java使用elasticsearch基础API使用案例讲解

    Java使用elasticsearch基础API使用案例讲解

    这篇文章主要介绍了Java使用elasticsearch基础API使用案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • Java+mysql实现学籍管理系统

    Java+mysql实现学籍管理系统

    这篇文章主要为大家详细介绍了Java+mysql实现学籍管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-07-07
  • Java多线程实现第三方数据同步

    Java多线程实现第三方数据同步

    这篇文章主要为大家详细介绍了Java多线程实现第三方数据同步,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • java对象转化成String类型的四种方法小结

    java对象转化成String类型的四种方法小结

    在java项目的实际开发和应用中,常常需要用到将对象转为String这一基本功能。本文就详细的介绍几种方法,感兴趣的可以了解一下
    2021-08-08
  • Spring整合Springmvc的相关介绍

    Spring整合Springmvc的相关介绍

    今天小编就为大家分享一篇关于Spring整合Springmvc的相关介绍,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • Kafka使用Java客户端进行访问的示例代码

    Kafka使用Java客户端进行访问的示例代码

    本篇文章主要介绍了Kafka使用Java客户端进行访问的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • SpringBoot实现前后端分离国际化的示例详解

    SpringBoot实现前后端分离国际化的示例详解

    Springboot国际化可以帮助使用者在不同语言环境中构建应用程序,这样应用程序可以有效地适应不同语言文化背景下的用户需求。本文主要介绍了SpringBoot实现前后端分离国际化的方法,需要的可以参考一下
    2023-02-02
  • java中Path和ClassPath用法比较

    java中Path和ClassPath用法比较

    在本篇文章里小编给大家分享了关于java中Path和ClassPath用法比较内容,有需要的朋友们学习下。
    2019-01-01

最新评论