【问题标题】:HttpServletRequest details returning null with @Async SpringHttpServletRequest 详细信息返回 null 与 @Async Spring
【发布时间】:2019-07-05 04:58:39
【问题描述】:

我想提取传入请求的 URI。

我的应用程序中有以下代码 - @RequestMapping,即 @Async。我想通过request.getRequestURI() 提取路径URI,但是当@Async 注释存在时它返回null,否则,当它不存在时,输出是所期望的。这是预期的行为,如果是,为什么?以及如何使用@Async 获得相同的输出?删除 @Async 对我来说不是一个简单的选择,因为我想用它来提高性能。

@Async
@RequestMapping("{name}/**")
@ResponseBody
public void incomingRequest(
        @PathVariable("name") String name,
        HttpMethod method,
        HttpServletRequest request,
        HttpServletResponse response)
{
    String URI = request.getRequestURI(); // <-- null with @Async
}

似乎总的来说,所有与请求相关的参数都在丢失,这不是我想要的;我需要为我的程序提取它们。

【问题讨论】:

  • 我在本地尝试过,因为它对我有用,所以我不确定你还有什么会导致 null。但是,我建议您创建一个服务类来获取您的请求数据并对其进行处理。您可以使用 @Async 而不是 Controller 来标记服务方法,并从您的控制器调用服务。

标签: java spring spring-boot tomcat servlets


【解决方案1】:

我能找到的最接近空HttpServletRequest原因的线索是对这篇帖子的答案的评论:What is a life of HttpServletRequest object?

要解决您的问题,您可以在此处尝试 2 种方法:

  1. 由于您的方法是 void,您可以手动从 incomingRequest 方法启动一个新线程,例如使用 CompletableFuture

  2. 或者,尝试从您的方法中返回 CompletableFuture,如下所示:

@Async
@RequestMapping("{name}/**")
@ResponseBody
public CompletableFuture<Void> incomingRequest(
        @PathVariable("name") String name,
        HttpMethod method,
        HttpServletRequest request,
        HttpServletResponse response)
{
    String URI = request.getRequestURI(); // should get the right non null path
    return CompletableFuture.completedFuture(null);
}

【讨论】:

  • 如果他返回一个 Callable,他还需要@Async 吗?我认为通过这样做,Spring 会知道异步执行。
  • 我不这么认为。如果没有注释,它仍然会在 http 请求线程上运行。你可以自己试试看当前线程。
  • 其实刚刚试了一下。它确实有效,但您必须返回一个 Callable,否则 lambda 将执行此操作 return () -&gt; {log.debug("callable:" + request.getRequestURI()); return null;};。更多信息在这里:spring.io/blog/2012/05/07/…。但无论哪种方式,OP 都没有理由变为 null,这是个谜。
  • 补充一下,我尝试了所有 4 种方式(@Asyc、常规普通方式、Callable 和 @Async + CompletableFuture)。在所有情况下,getRequestURI 都不是 null 并且是正确的值,所以我怀疑这里还有其他东西在起作用。
  • 当它发生时你使用什么路径?
猜你喜欢
  • 2018-11-10
  • 1970-01-01
  • 2020-09-18
  • 2022-08-22
  • 2017-10-03
  • 2014-07-17
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多