在服务器的并发请求数量比较大的时候,会产生很多的servlet线程(这些servlet线程在servlet容器的线程池中维护),如果每个请求需要耗费的时间比较长(比如,执行了一些IO的处理等),在之前的非异步的servlet中,这些servlet线程将会阻塞,严重耗费服务器的资源.而在servlet3.0中首次出现的异步servlet,通过一个单独的新的线程来执行这些比较耗时的任务(也可以把这些任务放到一个自己维护的线程池里),servlet线程立即返回servlet容器的servlet池以便响应其他请求,这样,在降低了系统的资源消耗的同时,也会提升系统的吞吐量
tomcat里面的一个Example:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
public class Async0 extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(Async0.class);
@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (Boolean.TRUE.equals(req.getAttribute("dispatch"))) {
log.info("Received dispatch, completing on the worker thread.");
log.info("After complete called started:"+req.isAsyncStarted());
resp.getWriter().write("Async dispatch worked:+"+System.currentTimeMillis()+"\n");
} else {
resp.setContentType("text/plain");
final AsyncContext actx = req.startAsync();
actx.setTimeout(Long.MAX_VALUE);
Runnable run = new Runnable() {
@Override
public void run() {
try {
req.setAttribute("dispatch", Boolean.TRUE);
Thread.currentThread().setName("Async0-Thread");
log.info("Putting AsyncThread to sleep");
Thread.sleep(2*1000);
log.info("Dispatching");
actx.dispatch();
}catch (InterruptedException x) {
log.error("Async1",x);
}catch (IllegalStateException x) {
log.error("Async1",x);
}
}
};
Thread t = new Thread(run);
t.start();
}
}
}
值得一提的是,异步的servlet并不会使客户端的访问速度加快,只是提升了服务器端的处理性能,减轻了服务器端的资源消耗,使得服务器端使用比较少的线程就能处理大量的连接,所以这个特性要在合适的场景下使用才可以
另外,异步的servlet的编程模型要比之前的servlet复杂许多,这也是在开发的时候需要注意的,jetty的continuations也提供了类似的功能,并且提供了简化的编程模型,在任何支持servlet3.0的容器里都可以运行(不是只能在jetty中运行),我们项目组开发的针对安卓客户端的消息推送服务器就使用到了jetty的这个机制,在之后的文章里总结一下
参考文章:
1、https://zhuanlan.zhihu.com/p/22018499?refer=tomcat
2、http://www.cnblogs.com/jiaoyiping/p/5979242.html
3、tomcat里面的example(如下图)