Spring 异步请求

作者 : jamin 本文共2744个字,预计阅读时间需要7分钟 发布时间: 2020-10-18 共1001人阅读

Spring 异步请求

官方文档 Asynchronous Request Processing

Servlet3.0

  1. 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.
  2. 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.
  3. 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.
//1、支持异步处理asyncSupported=true
@WebServlet(value="/async",asyncSupported=true)
public class HelloAsyncServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //2、开启异步模式
        AsyncContext startAsync = req.startAsync();

        //3、业务逻辑进行异步处理,开始异步处理
        startAsync.start(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    startAsync.complete();
                    //4、获取到异步上下文
                    AsyncContext asyncContext = req.getAsyncContext();
                    //5、获取响应
                    ServletResponse response = asyncContext.getResponse();
                    response.getWriter().write("hello async...");
                } catch (Exception e) {
                }
            }
        });
    }
}

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 asynchronous processing and submits the Callable to a TaskExecutor for processing in a separate thread.
  3. The DispatcherServlet and all Filter’s exit the Servlet container thread but the response remains open.
  4. The Callable produces a result and Spring MVC dispatches the request back to the Servlet container to resume processing.
  5. The DispatcherServlet is invoked again and processing resumes with the asynchronously produced result from the Callable.
@PostMapping
public Callable<String> processUpload(final MultipartFile file) {

    return new Callable<String>() {
        public String call() throws Exception {
            // ...
            return "someView";
        }
    };

}

DeferredResult

The sequence for DeferredResult is very similar except it’s up to the application to produce the asynchronous result from any 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 the DeferredResult 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.
@RequestMapping("/quotes")
@ResponseBody
public DeferredResult<String> quotes() {
    DeferredResult<String> deferredResult = new DeferredResult<String>();
    // Save the deferredResult somewhere..
    return deferredResult;
}

// In some other thread...
deferredResult.setResult(data);
本站所提供的部分资源来自于网络,版权争议与本站无关,版权归原创者所有!仅限用于学习和研究目的,不得将上述内容资源用于商业或者非法用途,否则,一切后果请用户自负。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源。如果上述内容资对您的版权或者利益造成损害,请提供相应的资质证明,我们将于3个工作日内予以删除。本站不保证所提供下载的资源的准确性、安全性和完整性,源码仅供下载学习之用!如用于商业或者非法用途,与本站无关,一切后果请用户自负!本站也不承担用户因使用这些下载资源对自己和他人造成任何形式的损失或伤害。如有侵权、不妥之处,请联系站长以便删除!
金点网络-全网资源,一网打尽 » Spring 异步请求

常见问题FAQ

免费下载或者VIP会员专享资源能否直接商用?
本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
是否提供免费更新服务?
持续更新,永久免费
是否经过安全检测?
安全无毒,放心食用

提供最优质的资源集合

立即加入 友好社区
×