【web.xml】
<filter>
<filter-name>normalFilter</filter-name>
<filter-class>net.mypla.controller.filter.AnyRequestFilter</filter-class>
<async-supported>true</async-supported> <!--请求启动AsyncContext必要声明-->
</filter> <filter-mapping>
<filter-name>normalFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher><!--只拦截普通请求-->
</filter-mapping> <filter>
<filter-name>forwardFilter</filter-name>
<filter-class>net.mypla.controller.filter.AnyRequestFilter</filter-class>
<async-supported>true</async-supported>
</filter> <filter-mapping>
<filter-name>forwardFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher><!--只拦截转发请求-->
</filter-mapping> <filter>
<filter-name>asyncFilter</filter-name>
<filter-class>net.mypla.controller.filter.AnyRequestFilter</filter-class>
<async-supported>true</async-supported>
</filter> <filter-mapping>
<filter-name>asyncFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ASYNC</dispatcher><!--拦截由AsyncContext派发的请求-->
</filter-mapping> 【AnyRequestFilter】
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
System.out.println("Entering " + this.name + ".doFilter().");
filterChain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) req), new HttpServletResponseWrapper((HttpServletResponse) resp));
//真正处理async请求
if (req.isAsyncSupported() && req.isAsyncStarted()) {
AsyncContext context = req.getAsyncContext();
System.out.println("Leaving " + this.name + ".doFilter(),async" +
"context holds wrapped req/resp = " +
!context.hasOriginalRequestAndResponse());
} else {
System.out.println("leaving " + this.name + ".doFilter().");
}
}
【异步Servlet】异步请求,关键代码
//过滤器有wrap这个动作,我们有收到unwrap的话就是不要wrap
//unwrap 原始参数启动异步 、 没有unwrap就用wrap后的req resp
final AsyncContext context = req.getParameter("unwrap")!=null?
req.startAsync():req.startAsync(req,resp);
//timeout 是请求参数 ?timeout=10000
context.setTimeout(timeout); System.out.println("Starting asynchronous thread.Request ID = "+id+"."); AsyncThread thread = new AsyncThread(id,context);
context.start(thread::doWork);
【异步线程】启动一个线程去处理,最终采用异步派发 而不是直接处理
public void doWork(){
System.out.println("Asynchronous thread started. Request ID = "+
this.id+".");
//当前线程休眠5秒
try {
Thread.sleep(5_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
//异步请求
HttpServletRequest request = (HttpServletRequest) this.context.getRequest();
System.out.println("Done sleeping. Request ID = "+this.id+
",URL="+request.getRequestURL()+".");
this.context.dispatch("/WEB-INF/jsp/filter/async.jsp");//异步派发,过滤器拦截。(如果AsyncContext直接处理掉请求,过滤器无法拦截。)
System.out.println("Asynchronous thread completed. Request ID = "+
this.id+".");
}