SpringMVC——Servlet3.0异步处理

开启异步:asyncSupported=true

@WebServlet(value="/path", asyncSupported=true)
public class AsyncServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// 主线程只负责开启副线程
    	AsyncContext startAsync = req.startAsync();
    	startAsync.start(() -> {
			// 异步处理 ... 
			startAsync.complete();
			AsyncContext asyncContext = req.getAsyncContext();
			ServletResponse response = asyncContext.getResponse();
			// 异步返回结果 response.getWriter()...
		})
    }
}

这里是自己开启线程,而SpringMVC会有一个异步处理线程池。
SpringMVCController层异步处理的方式:

  • 返回Callable<T>
  • 返回DeferredResult<T>

异步处理时,SpringMVC会把Callable的返回结果重发一次请求给servlet容器,所以servlet拦截器会拦截到两次,但是主线程不会触发后置拦截器,因为方法还没执行完。

posted @ 2020-12-14 19:29  qianbuhan  阅读(194)  评论(0)    收藏  举报