spring cloud微服务中多线程下,子线程通过feign调用其它服务,请求头token等丢失
在Spring Cloud微服务架构中,当在多线程环境下,子线程通过Feign客户端调用其他服务时,传递的请求头(例如:token)可能会丢失。这通常是因为默认情况下,Feign的请求作用域是基于线程安全的,但子线程可能没有继承父线程的请求头信息。
为了解决这个问题,你可以使用Feign的配置选项来确保请求头可以在子线程中传递。你可以通过实现Feign.Builder
定制器并配置它来实现这一点。以下是一个示例代码:
@Configuration
public class FeignConfig {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
@Bean
public feign.Request.Options requestOptions() {
return new feign.Request.Options(10000, 60000);
}
@Bean
public Feign.Builder feignBuilder() {
return Feign.builder()
.requestInterceptor(new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String value = request.getHeader(name);
template.header(name, value);
}
}
}
}
})
.contract(feignContract())
.requestInterceptor(new SpringSecurityFeignRequestInterceptor())
.options(requestOptions());
}
}
public class SpringSecurityFeignRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = re
评论已关闭