Spring 在 HystrixCommand 中无法访问 HttpServletRequest

Spring HttpServletRequest unaccessible in HystrixCommand

在注释为 @HystrixCommand 的 Javanica 中,我们正在检查请求是否在实际的 HTTP servlet 请求中,方法是检查:

RequestContextHolder.getRequestAttributes() != null;

然而,从 @HystrixCommand 调用此条件始终为假,即使请求来自 Spring MVC 请求。

如果我删除 @HystrixCommand 注释,一切正常。 我们还尝试直接使用 HttpServletRequest,效果很好(没有 @HystrixCommand):

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

带注释的 @HystrixCommand 我们面临异常,表明我不在有效的 HttpServletRequest 中。我知道这是由于 Hystrix 运行 命令在单独的线程中与它自己的线程池分开并尝试这样做,但也不起作用:

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
}

有人知道如何将 Spring HttpServletRequest 委托给 HystrixCommands 吗?

感谢任何帮助。

当默认使用 RequestContextHolder 时,它的参数是不共享的(有充分的理由!)。

假设您正在使用 DispatcherServlet 来处理您的请求,您可以将其 [threadContextInheritable] 设置为 true 以获得 RequestContextLocaleContext 在请求之间共享。

RequestContextFilter也是如此,RequestContextListener是不可能的。

注意: 我会考虑在线程之间共享 HttpServletRequest,这是你不应该做的事情,应该非常小心!