使用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已經被成功添加~
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet~
推薦閱讀:
- Spring Cloud Feign請求添加headers的實現方式
- SpringCloud全面解析@FeignClient標識接口的過程
- FeignClient如何共享Header及踩坑過程記錄
- Feign調用中的兩種Header傳參方式小結
- feign 打印日志不顯示的問題及解決