Spring Webflux弹性线程中获取Request对象

Ank*_*sal 3 requestcontext spring-webflux

我面临一个问题。我正在使用 Spring Webflux 并行调用一些 API。如果任何子线程遇到任何问题,它需要记录请求。现在的问题是,为了记录一个普通的 POJO 类,其中有一个静态方法可以通过 ApplicationContent 获取 bean 并将数据存储在队列中。

现在的问题是,我想访问请求参数,例如请求 URL / 控制器等。我尝试过

ServletRequestAttributes sra = 
        (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                    logger.error("====="+sra);
                    HttpServletRequest httpRequest = sra.getRequest();
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,sra为空。我尝试添加以下代码,

@Configuration
public class InheritableRequestContextListener extends RequestContextListener {
    private static final String REQUEST_ATTRIBUTES_ATTRIBUTE =
        InheritableRequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";

    @Override
    public void requestInitialized(ServletRequestEvent requestEvent) {
        System.out.println("111111111111111111");
        if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
            throw new IllegalArgumentException(
                    "Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
        }
        HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
        ServletRequestAttributes attributes = new ServletRequestAttributes(request);
        request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
        LocaleContextHolder.setLocale(request.getLocale());
        RequestContextHolder.setRequestAttributes(attributes, true);
    }
}
Run Code Online (Sandbox Code Playgroud)

但这没有帮助。任何人都可以帮忙。我使用的是springboot版本;2.0.2.发布

Tho*_*olf 5

您的实施不起作用有多种原因。

Webflux 与线程无关,这意味着任何线程都可以在应用程序中随时处理任何事情。如果应用程序发现切换当前执行线程是有效的,它就会这样做。

另一方面,Servlet 应用程序为每个请求分配一个线程,并在整个执行过程中坚持使用该线程。

如您所见,ApplicationContext 使用 ServletRequests,因此它在 Webflux 应用程序中不可用。它又使用threadlocal将请求对象存储到指定的线程。

在 webflux 中你不能使用 threadlocal,但是一旦应用程序切换线程,threadlocal 中的所有内容都会消失。这就是为什么你会得到空值。

那么如何在线程之间传递数据呢?

您需要做的是实现一个过滤器来拦截请求,提取您想要的信息并将其放入反应式上下文对象中。

https://projectreactor.io/docs/core/release/reference/#context

这是解决该问题的帖子。

https://developpaper.com/implementation-of-requestcontextholder-in-spring-boot-webflux/

  • 使用您尝试过的内容更新您的代码,或者提出一个包含上下文代码的新问题,指出哪些内容不起作用。 (2认同)