转:https://blog.csdn.net/benjamin_whx/article/details/38874657
13.1、概述
计算机的内存是有限的。Servlet/JSP容器的设计者很清楚这一点,因此他们提供了一些可以进行配置的设置,以确保容器能够在宿主机器中正常运行。例如,在Tomcat7中,处理进来请求的最多线程数量为200。如果是多处理器的服务器,则可以放心地增加线程数量,不过建议你还是尽量使用这个默认值。
Servlet或Filter一直占用着请求处理线程,直到它完成任务。如果完成任务花费了很长时间,并发用户的数量就会超过线程数量,容器将会遇到超出线程的风险。如果发生这种情况,TOmcat就会将超出的请求堆放在一个内部服务器Socket中(其他容器的处理方式可能会有所不同)。如果继续进来更多的请求,它们将会遭到拒绝,直到有资源可以处理请求为止。
异步处理特性可以帮助你节省容器线程。这项特性适用于长时间运行的操作。它的工作是等待任务完成,并释放请求处理线程,以便另一个请求能够使用该线程。注意,异步支持只适用于长时间运行的任务,并且你想让用户知道任务的执行结果。如果只有长时间运行的任务,但用户不需要知道处理的结果,那么则只要提供一个Runnable给Executor,并立即返回。例如,如果需要产生一份报表,并在保镖准备就绪之后通过电子邮件将报表发送出去,那么就不适合使用异步处理特性了。相反,如果需要产生一份报表,并且报表完成之后要展示给用户看,那么就可以使用异步处理。
13.2、编写异步的Servlet和Filter
WebServlet和WebFilter注解类型可以包含新的asyncSupport属性,为了编写能够支持异步处理的Servlet和Filter,asyncSupported属性必须设为true:
@WebServlet(asyncSupported=true...)
@WebFilter(asyncSupported=true...)
另一种在配置文件中配置
<servlet>
<servlet-name>AsyncServlet</servlet-name>
<servlet-class>servlet.MyAsyncServlet</servlet-class>
</servlet>
13.3、编写异步的Servlet
编写异步的Serlvet或Filter相对比较简单。如果你有一个任务需要相对比较长时间才能完成,最好创建一个异步的Servlet或者Filter,在异步的Servlet或者Filter类中需要完成以下工作:
1、在ServletRequest中调用startAsync方法。startAsync会返回一个AsyncContext。
2、在AsyncContext中调用setTimeout()方法,设置一个容器必须等待指定任务完成的毫秒数。这个步骤是可选的,但是如果没有设置这个时限,将会采用容器的默认时间。如果任务没能在规定实限内完成,将会抛出异常。
3、调用asyncContext.start方法,传递一个执行长时间任务的Runnable。
4、任务完成时,通过Runnable调用asyncContext.complete方法或者asyncContext.dispatch方法。
下面是异步Servlet的doGet或者doPost方法的主要内容:
final AsyncContext asyncContext = servletRequest.startAsync();
asyncContext.setTimeout( ... );
asyncContext.start(new Runnable(){
@Override
public void run(){
//long running task
asyncContext.complete() or asyncContext.dispatch()
}
})
下面是个例子:
AsyncDispatchServlet.java
-
package servlet;
-
-
import java.io.IOException;
-
-
import javax.servlet.AsyncContext;
-
import javax.servlet.ServletException;
-
import javax.servlet.annotation.WebServlet;
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
@WebServlet(name="AsyncDispatchServlet",
-
urlPatterns={"/asyncDispatch"},
-
asyncSupported=true)
-
public class AsyncDispatchServlet extends HttpServlet {
-
-
private static final long serialVersionUID = 1L;
-
@Override
-
public void doGet(final HttpServletRequest request,
-
HttpServletResponse response)
-
throws ServletException, IOException{
-
final AsyncContext asyncContext = request.startAsync() ;
-
request.setAttribute("mainThread", Thread.currentThread().getName());
-
asyncContext.setTimeout(5000);
-
asyncContext.start(new Runnable(){
-
-
@Override
-
public void run() {
-
try {
-
Thread.sleep(3000);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
request.setAttribute("workerThread", Thread.currentThread().getName());
-
asyncContext.dispatch("/ThreadNames.jsp");
-
}
-
-
});
-
}
-
}
ThreadNames.jsp
-
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
-
<%
-
String path = request.getContextPath();
-
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
-
%>
-
-
-
<html>
-
<head>
-
<base href="<%=basePath%>">
-
-
<title>Asynchronous Servlet</title>
-
-
<meta http-equiv="pragma" content="no-cache">
-
<meta http-equiv="cache-control" content="no-cache">
-
<meta http-equiv="expires" content="0">
-
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
-
<meta http-equiv="description" content="This is my page">
-
<!--
-
<link rel="stylesheet" type="text/css" href="styles.css">
-
-->
-
-
</head>
-
-
<body>
-
Main Thread:${mainThread}
-
<br/>
-
Worker Thread:${workerThread}
-
</body>
-
</html>
运行结果:
下面这个例子的Servlet每秒钟发送一次进程更新,以便用户能够追踪进程。它发送HTML响应和一个简单的javaScript代码,用来更新一个HTML div元素。
AsyncCompleteServlet.java
-
package servlet;
-
-
import java.io.IOException;
-
import java.io.PrintWriter;
-
-
import javax.servlet.AsyncContext;
-
import javax.servlet.ServletException;
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
-
public class AsyncCompleteServlet extends HttpServlet {
-
-
private static final long serialVersionUID = 1L;
-
-
@Override
-
public void doGet(HttpServletRequest request, HttpServletResponse response)
-
throws ServletException, IOException {
-
response.setContentType("text/html");
-
final PrintWriter writer = response.getWriter() ;
-
writer.println("<html><head><title>" +
-
"Async Servlet</title></head>");
-
writer.println("<body><div id='progress'></div>");
-
final AsyncContext asyncContext = request.startAsync() ;
-
asyncContext.setTimeout(60000);
-
asyncContext.start(new Runnable(){
-
-
@Override
-
public void run() {
-
System.out.println("new thread:" + Thread.currentThread());
-
for(int i=0; i<10; i++){
-
writer.println("<script>");
-
writer.println("document.getElementById(" +
-
"'progress').innerHTML = '" +
-
(i*10) + "% complete'");
-
writer.println("</script>") ;
-
writer.flush();
-
try {
-
Thread.sleep(1000);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
}
-
writer.println("<script>");
-
writer.println("document.getElementById(" +
-
"'progress').innerHTML='DONE'");
-
writer.println("</script>");
-
writer.println("</body></html>");
-
asyncContext.complete();
-
}
-
-
});
-
}
-
}
部署配置文件
-
-
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
-
<display-name>AsyncServlet</display-name>
-
<servlet>
-
<servlet-name>AsyncComplete</servlet-name>
-
<servlet-class>servlet.AsyncCompleteServlet</servlet-class>
-
<async-supported>true</async-supported>
-
</servlet>
-
<servlet-mapping>
-
<servlet-name>AsyncComplete</servlet-name>
-
<url-pattern>/asyncComplete</url-pattern>
-
</servlet-mapping>
-
</web-app>
运行结果:
13.4、异步监听器
除了支持Servlet和Filter执行异步操作之外,Servlet3.0还新增了一个AsyncListener接口,以便通知用户在异步处理期间发生的情况。AsyncListener接口定义了以下方法,当某个事件发生时,其中某一个方法就会被调用。
void onStartAsync(AsyncEvent event)
在刚启动一个异步操作时调用这个方法
void onComplete(AsyncEvent event)
当一个异步操作已经完成时调用这个方法
void onError(AsyncEvent event)
当一个异步操作失败时调用这个方法
void onTimeout(AsyncEvent event)
当一个异步操作已经超时的时候调用这个方法,即当它没能在规定时限内完成的时候。
这4个方法都会收到一个AsyncEvent事件,你可以分别通过调用它的getAsyncContext、getSuppliedReqeust和getSuppliedResponse方法从中获得相关的AsyncContext、ServletRequest和ServletResponse实例。
下面的例子和其他Web监听器不同的是,它没有用@WebListener标注AsyncListener的实现。
MyAsyncListener.java
-
package listener;
-
-
import java.io.IOException;
-
-
import javax.servlet.AsyncEvent;
-
import javax.servlet.AsyncListener;
-
-
public class MyAsyncListener implements AsyncListener{
-
-
@Override
-
public void onComplete(AsyncEvent arg0) throws IOException {
-
// TODO Auto-generated method stub
-
System.out.println("MyAsyncListener.onComplete()");
-
}
-
-
@Override
-
public void onError(AsyncEvent arg0) throws IOException {
-
// TODO Auto-generated method stub
-
System.out.println("MyAsyncListener.onError()");
-
}
-
-
@Override
-
public void onStartAsync(AsyncEvent arg0) throws IOException {
-
// TODO Auto-generated method stub
-
System.out.println("MyAsyncListener.onStartAsync()");
-
}
-
-
@Override
-
public void onTimeout(AsyncEvent arg0) throws IOException {
-
// TODO Auto-generated method stub
-
System.out.println("MyAsyncListener.onTimeout()");
-
}
-
-
}
AsyncListenerServlet.java
-
package servlet;
-
-
import java.io.IOException;
-
-
import javax.servlet.AsyncContext;
-
import javax.servlet.ServletException;
-
import javax.servlet.annotation.WebServlet;
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
-
import listener.MyAsyncListener;
-
@WebServlet(name="AsyncListenerServlet",
-
urlPatterns={"/asyncListener"},
-
asyncSupported=true)
-
public class AsyncListenerServlet extends HttpServlet{
-
-
private static final long serialVersionUID = 1L;
-
-
@Override
-
public void doGet(final HttpServletRequest request, HttpServletResponse response)
-
throws ServletException, IOException {
-
final AsyncContext asyncContext = request.startAsync() ;
-
asyncContext.setTimeout(5000);
-
asyncContext.addListener(new MyAsyncListener());
-
asyncContext.start(new Runnable(){
-
-
@Override
-
public void run() {
-
try {
-
Thread.sleep(3000);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
String greeting = "hi from listener" ;
-
System.out.println("wait...");
-
request.setAttribute("greeting", greeting);
-
asyncContext.dispatch("/index.jsp");
-
}
-
-
});
-
}
-
}