spring学习10- mvc 异步之servlet异步基础知识

来源:互联网 发布:linux find 文件 编辑:程序博客网 时间:2024/05/22 08:54

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:

  • 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 allowing some other thread to complete processing.
  • The call to request.startAsync() returns an AsyncContext, 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 current DispatcherType, which can be used to distinguish if a Servlet or a Filter 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.
0 0
原创粉丝点击