介绍
在微服务项目中,发现请求Header的loginId(用户的登录标识)在微服务A中调用的微服务B,loginId没有自动传递过去。
原因
当你使用Feign发起远程调用时,Feign会创建一个新的HTTP请求
去调用其他微服务。
这个新请求不会继承原始请求的所有Header。就像你在浏览器访问一个页面后点击跳转。
实现openFeign拦截器
1.实现RequestInterceptor
接口,在每次Feign发起远程调用前都会执行它的 apply() 方法。
ts
/**
* Feign请求拦截器
*/
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
if (Objects.nonNull(request)) {
String loginId = request.getHeader("loginId");
if (StringUtils.isNotBlank(loginId)) {
requestTemplate.header("loginId", loginId);
}
}
}
}
2.注册拦截器为Bean,供Feign使用
ts
@Configuration
public class FeignConfiguration {
@Bean
public RequestInterceptor requestInterceptor(){
return new FeignRequestInterceptor();
}
}
发现
在微服务使用openFeign进行debug时放行了3次,是由于Feign的默认重试。