19 Spring 异步请求
最后更新于
这有帮助吗?
最后更新于
这有帮助吗?
官方文档
A ServletRequest
can be put in asynchronous mode by calling request.startAsync()
. The main effect of doing so is that the Servlet, as well as any Filters, can exit but the response will remain open to allow processing to complete later.
The call to request.startAsync()
returns AsyncContext
which can be used for further control over async processing. For example it provides the method dispatch, that is similar to a forward from the Servlet API except it allows an application to resume request processing on a Servlet container thread.
The ServletRequest
provides access to the current DispatcherType
that can be used to distinguish between processing the initial request, an async dispatch, a forward, and other dispatcher types.
With the above in mind, the following is the sequence of events for async request processing with a Callable:
Controller returns a Callable
.
Spring MVC starts asynchronous processing and submits the Callable
to a TaskExecutor
for processing in a separate thread.
The DispatcherServlet
and all Filter’s exit the Servlet container thread but the response remains open.
The Callable
produces a result and Spring MVC dispatches the request back to the Servlet container to resume processing.
The DispatcherServlet
is invoked again and processing resumes with the asynchronously produced result from the Callable
.
The sequence for DeferredResult
is very similar except it’s up to the application to produce the asynchronous result from any thread:
Controller returns a DeferredResult
and saves it in some in-memory queue or list where it can be accessed.
Spring MVC starts async processing.
The DispatcherServlet
and all configured Filter’s exit the request processing thread but the response remains open.
The application sets the DeferredResult
from some thread and Spring MVC dispatches the request back to the Servlet container.
The DispatcherServlet
is invoked again and processing resumes with the asynchronously produced result.