Search code examples
springhystrix

Spring HttpServletRequest unaccessible in HystrixCommand


Inside a Javanica annotated @HystrixCommand we are checking if the request was in an actual HTTP servlet request by checking:

RequestContextHolder.getRequestAttributes() != null;

However invoked from a @HystrixCommand this condition is always false, even if the request came from a Spring MVC request.

If I remove the @HystrixCommand annotation everything works fine. We also tried to use the HttpServletRequest directly, this works fine (without @HystrixCommand):

LOGGER.info(request.getHeader("X-Client"));

With annotated @HystrixCommand we are facing exception indicating I am not in an valid HttpServletRequest. I know it is due to Hystrix running commands in separate Threads from its own ThreadPool and tried to do this, but doesn't work either:

public class RequestServletFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // No Impl
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        chain.doFilter(request, response);
    } finally {
        context.shutdown();
    }
}

@Override
public void destroy() {
    // No Impl
}

Does someone have a clue how to delegate the Spring HttpServletRequest into HystrixCommands?

Any help is appreciated.


Solution

  • When using the RequestContextHolder by default it parameters are not shared (for good reasons!).

    Assuming that you are using a DispatcherServlet to handle your request you can set its [threadContextInheritable] to true to have the RequestContext and LocaleContext shared between requests.

    The same applies for the RequestContextFilter, it isn't possible with the RequestContextListener.

    Note: I would consider sharing the HttpServletRequest between threads as something you shouldn't be doing and should be done with great care!