0

I have two spring boot services. A and B.

From A service, I am calling B Service(Using Feign Client). I have one request interceptor which adds custom headers to the request before sending it.

This is my interceptor:

public class HeaderInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate template) {       
        try {
            Object encrypyedData = RequestContextHolder.currentRequestAttributes().getAttribute(""headerName", 0);
            if(encrypyedData != null) {
                template.header("headerName", encrypyedData.toString());
            }else {
                System.out.println("Encrypted Data is NULL");
            }
        } catch(Exception e) {
            System.out.println("ankit === "+e.getMessage());
        }

    }

}

But when I am running this code, I am getting exception : No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

I have also tried adding this in Service A

@Bean public RequestContextListener requestContextListener(){
   return new RequestContextListener();
} 

I have added this in Main Application File(file annotated with @SpringBootApplication).

Still the same issue. What am i missing?

Ankit Bansal
  • 2,162
  • 8
  • 42
  • 79

1 Answers1

1

Probably you're running your spring cloud feign on Hystrix. Hystrix's default isolation mode is thread, so actual HTTP request will be called on the different thread that is managed by hystrix. And HeaderInterceptor also run on that thread.

But, you are accessing RequestContextHolder and it is using ThreadLocal. That is probably the reason for your error.

Try to use one of the the below properties on A service.

It will disable hystrix for feign.

feign:
  hystrix:
    enabled: false

Or, you can just change isolation mode of your hystrix like below.

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: SEMAPHORE

If it works, you need to choose the way that you apply to. Just disable hystrix or change isolation strategy or just passing attribute via another way.

yongsung.yoon
  • 5,489
  • 28
  • 32
  • No i am not using hystrix. but i am using rxjava. that is what causing the issue since it is not creating new threads and using the old threads. – Ankit Bansal Apr 06 '18 at 16:26