Servlet3.0 开启异步两种方式

 

Servlet3.0 开启异步两种方式:

方式一:web.xml形式

  <servlet>      

    <servlet-name>async0</servlet-name>      

    <servlet-class>async.Async0</servlet-class>      

     <async-supported>true</async-supported>    

  </servlet>

方式二:@WebServlet

@WebServlet(urlPatterns = "/DemoClass", asyncSupported = true)  --在类上的注解

Tomcat7源码中的示例代码如下:     

 1     @Override
 2     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 3         final AsyncContext actx = req.startAsync();
 4         actx.setTimeout(30 * 1000);
 5         Runnable run = new Runnable() {
 6             @Override
 7             public void run() {
 8                 try {
 9                     Thread.currentThread().setName("Async2-Thread");
10                     log.info("Putting AsyncThread to sleep");
11                     Thread.sleep(2 * 1000);
12                     log.info("Writing data.");
13                     actx.getResponse().getWriter()
14                             .write("Output from background thread. Time:" + System.currentTimeMillis() + "\n");
15                     actx.complete();
16                 } catch (InterruptedException x) {
17                     log.error("Async2", x);
18                 } catch (IllegalStateException x) {
19                     log.error("Async2", x);
20                 } catch (IOException x) {
21                     log.error("Async2", x);
22                 }
23             }
24         };
25         Thread t = new Thread(run);
26         t.start();
27     }

“异步的servlet并不会使客户端的访问速度加快,只是提升了服务器端的处理性能,减轻了服务器端的资源消耗,使得服务器端使用比较少的线程就能处理大量的连接。”--摘自http://www.cnblogs.com/jiaoyiping/p/6130503.html

posted @ 2018-04-11 16:21  jintian315  阅读(223)  评论(0编辑  收藏  举报