Feign remote call missing request header problem

RequestInterceptor configuration

The underlying RequestContextHolder is a Thread Local

@Configuration
public class GrainmallFeginConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor  requestInterceptor(a){
       return new RequestInterceptor(){

           @Override
           public void apply(RequestTemplate template) {

               // Use RequestContextHolder to get the incoming request
               ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
               HttpServletRequest request = requestAttributes.getRequest();  // Old requests (with cookies). If not synchronized, Fegin will create a new request by default without cookies
               // Synchronize request header data Cookie
              if(request! =null) {
               String cookie = request.getHeader("Cookie");
               // The cookie of the old request is synchronized to the new request
               template.header("Cookie",cookie);
              }
               System.out.println("Perform the requestInterceptor. apply method before feign remote"); }}; }}Copy the code

The problem is that this only works in a single thread, and if we do it asynchronously, we lose context

Solution: 1. Get the original request:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

2. Add the following to the thread that needs to share data:

RequestContextHolder.setRequestAttributes(requestAttributes)