时间:2022-10-17 11:20:43 | 栏目:JAVA代码 | 点击:次
我们在调用feign的情况下,经常需要用到客户端所持有的header比如说auth-token,我们需要将这些header传递下去
使用拦截器,在客户端拦截feign的请求,并把所需要的header传递下去
代码:
@Configuration public class FeignInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { Map<String,String> headers = getHeaders(getHttpServletRequest()); for(String headerName : headers.keySet()){ requestTemplate.header(headerName, getHeaders(getHttpServletRequest()).get(headerName)); } } private HttpServletRequest getHttpServletRequest() { try { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } catch (Exception e) { e.printStackTrace(); return null; } } private Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); if(needThisHeader(key)){ String value = request.getHeader(key); map.put(key, value); } } return map; } private boolean needThisHeader(String headerName){ //todo:这里写你的逻辑,哪些header需要传递,千万不能把所有的header传下去 return true; } }
@Configuration public class FeignSupportConfig { /** * feign请求拦截器 * * @return */ @Bean public RequestInterceptor requestInterceptor(){ return new FeignInterceptor(); } }
一定不能把所有的header都往下传,这样很可能会导致在调用feign的时候,请求类型混乱,应该需要哪些header就穿哪些header
今天尝试用feign去调用其他部门提供的一个HTTP接口,该接口要求在请求中设置一个username头部,用于身份鉴权。
@FeignClient(name = "kafka-client", url = "http://kafka.xxx.com") public interface KafkaClient { @GetMapping(value = "/api/clusterManager/listTopics") @Headers( {"cache-control: no-cache", "username: wangyong@xxx.com"}) TopicsResponse listTopics(@RequestParam("clusterName") String clusterName, @RequestParam("clusterArea") String clusterArea); }
代码写好好,尝试去进行访问
{ "timestamp": 1551768926170, "status": 500, "error": "Internal Server Error", "exception": "com.netflix.zuul.exception.ZuulException", "message": "pre:AuthAccessFilter" }
异常堆栈信息如下:
at feign.FeignException.errorStatus(FeignException.java:62)
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:91)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:134)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
at com.sun.proxy.$Proxy147.listTopics(Unknown Source)
at com.yidian.data.exptmgr.controller.KafkaController.getKafkaTopics(KafkaController.java:35)
// 省略更多异常堆栈信息
于是我尝试通过debug来找到问题的根源,通过debug我发现feign会先将请求参数构建成Request对象,request信息如下:
request
从图中可看到,该Request实例的headers属性为空,而Request又是根据RequestTemplate模板对象生成的,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需要用“=”进行分割。
于是我修改成下面的形式,
@GetMapping(value = "/api/clusterManager/listTopics", headers = {"cache-control=no-cache", "username=wangyong@xxx.com"}) TopicsResponse listTopics(@RequestParam("clusterName") String clusterName, @RequestParam("clusterArea") String clusterArea);