在实际工作中我们会遇到一些耗时操作,这个时候如果不能及时response 就会返回失败,想要执行异步操作,延时返回数据,可以使用以下方法
使用asyncSupported = true
注解
@WebServlet(name = "apitest", asyncSupported = true)
如果不使用这注解,访问时则会报错
以下是源码
@WebServlet(name = "apitest", asyncSupported = true)
public class apitest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
private volatile ExecutorService executorService;
@Override
public void init() throws ServletException {
super.init();
//newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
executorService = Executors.newFixedThreadPool(100);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AsyncContext asyncCtx = request.startAsync();
executorService.submit(new Runnable() {
@Override
public void run() {
//延时5秒 ,模拟耗时操作
try {
Thread.sleep (5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrintWriter writer = null;
try {
writer = asyncCtx.getResponse().getWriter();
} catch (IOException e) {
e.printStackTrace();
}
//返回数据
writer.println("servlevt异步处理成功");
writer.flush();//记得关闭
asyncCtx.complete();//记得关闭
}
}, asyncCtx);
}
}
重启tomcat,访问接口/apitest , 可以看见,等待了5秒后,返回了servlevt异步处理成功。thread.sleep() , 这个一般不需要,实际应用中写耗时操作就行。