在 Spring Cloud 中,Feign 是一个声明式的HTTP客户端,用于简化微服务之间的REST通信。Feign提供了许多功能,包括RequestInterceptor,用于自定义和修改发出的HTTP请求。RequestInterceptor 是一个接口,允许您在发出Feign请求之前对请求进行干预和修改。
package feign;
public interface RequestInterceptor {
/**
* Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
*/
void apply(RequestTemplate template);
}
RequestInterceptor 接口通常用于以下场景:
配置身份验证信息: 您可以使用 RequestInterceptor 在每个Feign请求中添加身份验证token、密钥等。
动态配置URL: RequestInterceptor 可以支持动态配置服务url。
要使用 RequestInterceptor,您需要创建一个实现该接口的类,并在 apply 方法中定义要执行的自定义逻辑。然后,您可以将该拦截器注册到 Feign 客户端中,以确保它会在每个请求中执行。
在SpringCloud Feign 中,默认实现了一些 RequestInterceptor,这些拦截器用于处理一些常见的请求和处理逻辑。比如可以在请求头中添加基本身份验证信息的BasicAuthRequestInterceptor;用于设置请求头中的Accept,指定期望相应内容的FeignAcceptHeaderRequestInterceptor;用于启用请求和相应GZIP压缩编码的FeignContentGzipEncodingInterceptor以及来添加OAuth2认证相关信息的OAuth2FeignRequestInterceptor。而这些默认实现的拦截器由于没有使用@Order,所以优先级为默认的最低。
以下为RequestInterceptor的使用演示:
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
public class AuthorizationRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
//可以在此处自行定义逻辑,比如在请求头中添加token
template.header("Authorization", "Bearer AccessToken");
}
}
import org.springframework.context.annotation.Bean;
import feign.RequestInterceptor;
@Configuration
public class FeignClientConfiguration {
@Bean
public RequestInterceptor AuthorizaitonRequestInterceptor() {
return new AuthorizaitonRequestInterceptor();
}
}