1. feign.RequestInterceptor介绍
1.1 用途
老外是这么说的:
When you need to change all requests, regardless of their target,
you’ll want to configure a RequestInterceptor. For example, if you are
acting as an intermediary, you might want to propagate the
X-Forwarded-For header。
意思就是当使用Feign客户端进行服务之间的交互时,可以使用RequestInterceptor
来修改请求的相关信息,比如Header。
1.2 代码
public interface RequestInterceptor {
void apply(RequestTemplate var1);
}
当把这个RequestInterceptor
注入到容器后,所有Feign请求都会经过这个方法,因此我们可以在这个apply中去修改请求的相关参数,从而完成诸如认证,鉴权之类参数的设置。
2.2 使用feign.RequestInterceptor完成Xxl登录认证
@Slf4j
@Component(XxlJobAuthInterceptor.NAME)
public class XxlJobAuthInterceptor implements RequestInterceptor {
public static final String NAME = "XxlJobAuthInterceptor";
@Autowired
private XxlJobUserApi xxlJobUserApi;
private final String LOGIN_IDENTITY_KEY = "XXL_JOB_LOGIN_IDENTITY";
@Value("${xxl.username}")
private String username;
@Value("${xxl.password}")
private String password;
@Override
public void apply(RequestTemplate requestTemplate) {
Response loginResponse = xxlJobUserApi.login(username, password, "off");
Map<String, Collection<String>> headers = loginResponse.headers();
Collection<String> acceptCookies = headers.get(HttpHeader.SET_COOKIE.lowerCaseName());
requestTemplate.header(HttpHeader.COOKIE.name(),acceptCookies);
}
}
我这里是用来登录Xxl-Job,其它的系统间认证完全可以使用相同的思路搞定。