本文最后更新于:2022年9月30日 下午
                  
                
              
            
            
              
              起因
客户端带请求头请求接口–>接口调用其他服务的接口会导致请求头丢失问题
例子:有两个服务A和B,都加了认证拦截器,客户端调用服务A接口时会携带cookie请求头信息,经过服务A认证拦截器后调用服务B接口,在经过服务B拦截器时会发现请求头cookie丢失问题
原因
Feign 远程调用时会生成代理对象,代理对象调用时会经过一些逻辑判断和一系列的拦截器,构造出新的Request对象,Request默认为空,所以导致请求头丢失问题
解决
如果生成代理对象后再经过我们定义的拦截器,将请求头加上去再调用远程服务就可以解决这个问题;

| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 
 | import feign.RequestInterceptor;import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.context.request.RequestContextHolder;
 import org.springframework.web.context.request.ServletRequestAttributes;
 
 import javax.servlet.http.HttpServletRequest;
 
 
 
 
 @Configuration
 public class FeignConfig {
 
 @Bean("requestInterceptor")
 public RequestInterceptor requestInterceptor() {
 
 RequestInterceptor requestInterceptor = template -> {
 
 ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 
 if (requestAttributes != null) {
 HttpServletRequest request = requestAttributes.getRequest();
 
 String token = request.getHeader("token");
 template.header("token", token);
 }
 };
 
 return requestInterceptor;
 }
 }
 
 | 
源码

References