亲宝软件园·资讯

展开

Feign调用服务Headers传参

猹里。 人气:12

Feign调用服务Headers传参

在使用springcloud中经常会出现个服务调用,一般情况下会在Headers加上token的验证,那么在feign调用时候我们怎么去传这个token过去呢,有人会用@Headers这个注解来实现。但是这样方法太多笨重。

我们可以使用RequestInterceptor来实现

附上代码

    import feign.RequestInterceptor;
    import feign.RequestTemplate;
    import org.springframework.stereotype.Component;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    import javax.servlet.http.HttpServletRequest;
    import java.util.Enumeration;
    @Component
    public class SecuringRequestInterceptor implements RequestInterceptor {
        @Override
        public void apply(RequestTemplate requestTemplate) {
            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("Ttoken");
                    requestTemplate.header("Ttoken", values);
                }
            }
        }
    }

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已经被成功添加

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

加载全部内容

相关教程
猜你喜欢
用户评论