59、servlet3.0-异步请求
59.1 开启servlet异步请求步骤
- 支持异步处理
asyncSupported=true
- 开启异步模式
req.startAsync();
- 业务逻辑进行异步处理;开始异步处理
asyncContext.start()
- 获取响应
asyncContext.getResponse()
59.2 新建异步servlet处理类
@WebServlet(value = "/async", asyncSupported = true)
public class HelloAsyncServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AsyncContext asyncContext = req.startAsync();
System.out.println("主线程开始:" + Thread.currentThread() + "start..." + System.currentTimeMillis());
asyncContext.start(() -> {
try {
System.out.println("子线程开始:" + Thread.currentThread() + "start..." + System.currentTimeMillis());
sayHello();
asyncContext.complete();
ServletResponse response = asyncContext.getResponse();
response.getWriter().write("异步执行完成");
System.out.println("子线程结束:" + Thread.currentThread() + "end..." + System.currentTimeMillis());
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
});
System.out.println("主线程结束:" + Thread.currentThread() + "end..." + System.currentTimeMillis());
}
public void sayHello() throws InterruptedException {
System.out.println("主线程运行:" + Thread.currentThread() + "processing..." + System.currentTimeMillis());
Thread.sleep(3000);
}
}
59.3 测试用例