其他分享
首页 > 其他分享> > servlet3.0实现异步请求处理

servlet3.0实现异步请求处理

作者:互联网

基于servlet3.0注解版异步处理现实步骤:

步骤

1.1:通过@WebServlet注解拦截/async请求,支持异步处理必须声明syncSupported = true

@WebServlet(value="/async",asyncSupported=true)

1.2:开启异步任务

AsyncContext  startAsync = req.startAsync();

startAsync.start(new Runnable() {
@Override
public void run() {

 

//处理业务逻辑

}
});

1.3:结束异步任务

startAsync.complete();

 

 

2、源码实现:

package com.atguigu.servlet;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value="/async",asyncSupported=true)
public class HelloAsyncServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、支持异步处理asyncSupported=true
//2、开启异步模式
System.out.println("主线程开始...."+Thread.currentThread());
AsyncContext startAsync = req.startAsync();

//3、业务逻辑进行异步处理
startAsync.start(new Runnable() {
@Override
public void run() {
try {
System.out.println("副线程开始...."+Thread.currentThread());
sayHello();

//获取到异步的上下文
AsyncContext asyncContext = req.getAsyncContext();
//获取响应
ServletResponse response= asyncContext.getResponse();
response.getWriter().write("hello asynce.....");

startAsync.complete();//注意complete方法必须在逻辑处理完成之后添加,否则会出先异常
System.out.println("副线程结束...."+Thread.currentThread());
} catch (Exception e) {
e.printStackTrace();
}
}
});
System.out.println("主线程结束...."+Thread.currentThread());
}

public void sayHello() throws Exception{
System.out.println(Thread.currentThread()+"processing..........");
Thread.sleep(3000);
}
}

 

3、测试

打开浏览器,输入地址:http://localhost:8080/servlet3.0/async

注:主线程会立即释放,任务交由副线程处理。

 

标签:异步,servlet3.0,请求,Thread,import,startAsync,servlet,javax
来源: https://www.cnblogs.com/wdandan/p/14994031.html