点击上方“Java秃头哥”,选择“星标”
每天分享优质干货
作者 | 会炼钢的小白龙
来源 | cnblogs.com/baixianlong/p/10661591.html
一、Spring Boot 中异步请求的使用 **
1、异步请求与同步请求
![8e7ad1fe2eb17fe69de0c6ef1f25afc5.png](https://i-blog.csdnimg.cn/blog_migrate/ebe8cacfd41ce4ced347f736e6bf7d81.jpeg)
![f608cc34ec0bff787bd118644659b1ab.png](https://i-blog.csdnimg.cn/blog_migrate/bddbc5ff8c6153ae2c9719ba83bfeaf4.jpeg)
2、异步请求的实现
方式一:Servlet 方式实现异步请求@RequestMapping(value = "/email/servletReq", method = GET)
public void servletReq (HttpServletRequest request, HttpServletResponse response) {
AsyncContext asyncContext = request.startAsync();
//设置监听器:可设置其开始、完成、异常、超时等事件的回调处理
asyncContext.addListener(new AsyncListener() {
@Override
public void onTimeout(AsyncEvent event) throws IOException {
System.out.println("超时了...");
//做一些超时后的相关操作...
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
System.out.println("线程开始");
}
@Override
public void onError(AsyncEvent event) throws IOException {
System.out.println("发生错误:"+event.getThrowable());
}
@Override
public void onComplete(AsyncEvent event) throws IOException {
System.out.println("执行完成");
//这里可以做一些清理资源的操作...
}
});
//设置超时时间
asyncContext.setTimeout(20000);
asyncContext.start(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);
System.out.println("内部线程:" +