This may be difficult to understand without any knowledge of the Servlet 3 async processing feature. It would certainly help to read up on it. At a very minimum consider the following basic facts:
- A
ServletRequest
can be put in asynchronous mode by callingrequest.startAsync()
. The main effect of doing so is that the Servlet, as well as any Filters, can exit but the response will remain open allowing some other thread to complete processing. - The call to
request.startAsync()
returns anAsyncContext
, which can be used for further control over async processing. For example it provides the methoddispatch
, which can be called from an application thread in order to "dispatch" the request back to the Servlet container. An async dispatch is similar to a forward except it is made from one (application) thread to another (Servlet container) thread whereas a forward occurs synchronously in the same (Servlet container) thread. ServletRequest
provides access to the currentDispatcherType
, which can be used to distinguish if aServlet
or aFilter
is processing on the initial request processing thread and when it is processing in an async dispatch.
spring mvc 异步功能
1)Callable形式:
With the above in mind, the following is the sequence of events for async request processing with a
Callable
:
(1) Controller returns a Callable
,
(2) Spring MVC starts async processing and submits the Callable
to
a TaskExecutor
for
processing in a separate thread, (3) the DispatcherServlet
and
all Filter’s exit the request processing thread but the response remains open, (4) the Callable
produces
a result and Spring MVC dispatches the request back to the Servlet container, (5) theDispatcherServlet
is
invoked again and processing resumes with the asynchronously produced result from the Callable
.
The exact sequencing of (2), (3), and (4) may vary depending on the speed of execution of the concurrent threads.2)DefferedResult形式:
The
sequence of events for async request processing with a
DeferredResult
is
the same in principal except it’s up to the application to produce the asynchronous result from some thread: (1) Controller returns a DeferredResult
and
saves it in some in-memory queue or list where it can be accessed, (2) Spring MVC starts async processing, (3) the DispatcherServlet
and
all configured Filter’s exit the request processing thread but the response remains open, (4) the application sets theDeferredResult
from
some thread and Spring MVC dispatches the request back to the Servlet container, (5) the DispatcherServlet
is
invoked again and processing resumes with the asynchronously produced result.