在做接口请求时,我们经常会在header头中增加一些鉴权信息,如token 或 jwt,那么在通过fegin从A server去调用B server的接口时,如果B server的接口需要header信息,我们需要将A sever获取的header转发到B上。
解决方式
我们需要实现Feign提供的一个接口RequestInterceptor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @Configuration public class FeignConfiguration implements RequestInterceptor{ private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void apply(RequestTemplate template) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String values = request.getHeader(name); template.header(name, values); } logger.info("feign interceptor header:{}",template); } } }
|
在@FeignClient
注解里面的属性加上configuration = FeignConfiguration.class
就可以了。如
1 2 3 4 5
| @FeignClient(value = "xinmusic-music",configuration = FeignConfig.class) @RequestMapping("/music") public interface MusicService { }
|