HttpServletRequest 详细信息使用 @Async Spring 返回 null [英] HttpServletRequest details returning null with @Async Spring
问题描述
我想提取传入请求的 URI.
I would like to extract the URI of an incoming request.
我的应用程序中有以下代码 - @RequestMapping
是 @Async
.我想通过 request.getRequestURI()
提取路径 URI,但是当 @Async
注释存在时它返回 null
,否则,当事实并非如此,输出符合要求.这是预期的行为,如果是,为什么?以及如何使用 @Async
获得相同的输出?删除 @Async
对我来说不是一个简单的选择,因为我想用它来提高性能.
I have the following code in my application - a @RequestMapping
which is @Async
. I would like to extract the path URI via request.getRequestURI()
but it returns null
when the @Async
annotation is present, otherwise, when it is not, the output is as desired. Is this intended behaviour, if so, why? And how can I obtain the same output with @Async
? Removing @Async
is not an easy option for me as I would like to use it for performance.
@Async
@RequestMapping("{name}/**")
@ResponseBody
public void incomingRequest(
@PathVariable("name") String name,
HttpMethod method,
HttpServletRequest request,
HttpServletResponse response)
{
String URI = request.getRequestURI(); // <-- null with @Async
}
好像一般情况下所有请求相关的参数都丢失了,这不是我想要的;我需要为我的程序提取它们.
It seems that in general, all request related parameters are being lost, which is not what I want; I need to extract them for my program.
推荐答案
我能找到的最接近 HttpServletRequest
空的原因的线索是对这个帖子的答案的评论:HttpServletRequest 对象的生命周期是什么?
The closest clue to the reason of empty HttpServletRequest
I could find was comment to the answer on this post: What is a life of HttpServletRequest object?
要解决您的问题,您可以在这里尝试两种方法:
To solve your issue you can try 2 approaches here:
由于您的方法是
void
,您可以从incomingRequest
方法手动启动一个新线程,例如使用 CompletableFuture.
Since your method is
void
you can manually start a new thread fromincomingRequest
method using, for example, CompletableFuture.
或者,尝试从您的方法中返回 CompletableFuture
,如下所示:
Or, try with returning CompletableFuture
from your method, like so:
@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);
}
这篇关于HttpServletRequest 详细信息使用 @Async Spring 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!