Spring Cloud Feign请求拦截器的使用

Feign 支持请求拦截器,在发送请求前,可以对发送的模板进行操作,例如设置请求头等属性,自定请求拦截器需要实现 feign.RequestInterceptor 接口,该接口的方法 apply 有参数 template ,该参数类型为 RequestTemplate,我们可以根据实际情况对请求信息进行调整,示例如下:

实现RequestInterceptor接口

import feign.RequestInterceptor;
import feign.RequestTemplate;

public class MyRequestInterceptor implements RequestInterceptor {
    public void apply(RequestTemplate template) {
        template.header("Authorization", "token:9du2a12hdc72dead018");
    }
}

创建拦截器

MyClient client = Feign.builder().requestInterceptor(new MyRequestInterceptor())
			.target(MyClient.class,"http://localhost:8080/");

测试验证

由于在默认情况下,不会记录接口的日志,如果需要了解接口的调用情况,可以使用 logLevel 方法进行配置日志级别:

  • NONE:默认值,不进行日志记录
  • BASIC:记录请求方法、URL、响应状态代码和执行时间
  • HEADERS:除了 BASIC 记录的信息外,还包括请求头和响应头
  • FULL:记录全部日志,包括请求头、请求体、请求与响应的元数据
MyClient client = Feign.builder().client(new MyClient()).requestInterceptor(new MyRequestInterceptor())
			.logLevel(Logger.Level.FULL)
			.logger(new Logger.JavaLogger().appendToFile("E:\\Temp\\logs\\order.log"))
			.requestInterceptor(new MyRequestInterceptor())
			.target(MyClient.class,"http://localhost:8080/");

client.findOrder("87878")

启动项目,然后查看日志如下:

[MyClient#order] ---> GET http://localhost:8080/order?body=is+body HTTP/1.1
[MyClient#order] Authorization: token:9du2a12hdc72dead018
[MyClient#order] ---> END HTTP (0-byte body)
[MyClient#order] <--- HTTP/1.1 200 (790ms)
[MyClient#order] content-length: 23
[MyClient#order] content-type: text/plain;charset=UTF-8
[MyClient#order] date: Thu, 15 Apr 2019 11:00:11 GMT
[MyClient#order] x-application-context: helloworld-provider:8080
[MyClient#order]
[MyClient#order] order is body port:8080
[MyClient#order] <--- END HTTP (23-byte body)

在请求头中,已经增加了 Authorization: token:9du2a12hdc72dead018 数据

0

发表评论

您的电子邮箱地址不会被公开。