Servlet 3特性:異步Servlet

理解異步Servlet以前,讓咱們試着理解爲何須要它。假設咱們有一個Servlet須要不少的時間來處理,相似下面的內容: html

LongRunningServlet.java java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
packagecom.journaldev.servlet;
 
importjava.io.IOException;
importjava.io.PrintWriter;
 
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
 
@WebServlet("/LongRunningServlet")
publicclassLongRunningServletextendsHttpServlet {
    privatestaticfinallongserialVersionUID = 1L;
 
    protectedvoiddoGet(HttpServletRequest request,
            HttpServletResponse response)throwsServletException, IOException {
        longstartTime = System.currentTimeMillis();
        System.out.println("LongRunningServlet Start::Name="
                + Thread.currentThread().getName() +"::ID="
                + Thread.currentThread().getId());
 
        String time = request.getParameter("time");
        intsecs = Integer.valueOf(time);
        // max 10 seconds
        if(secs >10000)
            secs =10000;
 
        longProcessing(secs);
 
        PrintWriter out = response.getWriter();
        longendTime = System.currentTimeMillis();
        out.write("Processing done for "+ secs +" milliseconds!!");
        System.out.println("LongRunningServlet Start::Name="
                + Thread.currentThread().getName() +"::ID="
                + Thread.currentThread().getId() +"::Time Taken="
                + (endTime - startTime) +" ms.");
    }
 
    privatevoidlongProcessing(intsecs) {
        // wait for given time before finishing
        try{
            Thread.sleep(secs);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
 
}

若是咱們的URL是:http://localhost:8080/AsyncServletExample/LongRunningServlet?time=8000 apache

獲得響應爲「Processing done for 8000 milliseconds! !「。如今,若是你會查看服務器日誌,會獲得如下記錄: 服務器

1
2
LongRunningServlet Start::Name=http-bio-8080-exec-34::ID=103
LongRunningServlet Start::Name=http-bio-8080-exec-34::ID=103::Time Taken=8002 ms.

因此Servlet線程實際運行超過 8秒,儘管大多數時間用來處理其它Servlet請求或響應。 session

這可能致使線程飢餓——由於咱們的Servlet線程被阻塞,直到全部的處理完成。若是服務器的請求獲得了不少過程,它將達到最大Servlet線程限制和進一步的請求會拒絕鏈接錯誤。 app

Servlet 3.0以前,這些長期運行的線程容器特定的解決方案,咱們能夠產生一個單獨的工做線程完成耗時的任務,而後返回響應客戶。Servlet線程返回Servlet池後啓動工做線程。Tomcat 的 Comet、WebLogic FutureResponseServlet 和 WebSphere Asynchronous Request Dispatcher都是實現異步處理的很好示例。 框架

容器特定解決方案的問題在於,在不改變應用程序代碼時不能移動到其餘Servlet容器。這就是爲何在Servlet3.0提供標準的方式異步處理Servlet的同時增長異步Servlet支持。 異步

實現異步Servlet async

讓咱們看看步驟來實現異步Servlet,而後咱們將提供異步支持Servlet上面的例子: ide

  1. 首先Servlet,咱們提供異步支持 Annotation @WebServlet  的屬性asyncSupported 值爲true。
  2. 因爲實際實現委託給另外一個線程,咱們應該有一個線程池實現。咱們能夠一個經過Executors framework 建立線程池和使用servlet context listener來初始化線程池。
  3. 經過ServletRequest.startAsync方法獲取AsyncContext的實例。AsyncContext提供方法讓ServletRequest和ServletResponse對象引用。它還提供了使用調度方法將請求轉發到另外一個 dispatch() 方法。
  4. 編寫一個可運行的實現,咱們將進行重處理,而後使用AsyncContext對象發送請求到另外一個資源或使用ServletResponse編寫響應對象。一旦處理完成,咱們經過AsyncContext.complete()方法通知容器異步處理完成。
  5. 添加AsyncListener實現AsyncContext對象實現回調方法,咱們可使用它來提供錯誤響應客戶端裝進箱的錯誤或超時,而異步線程處理。在這裏咱們也能夠作一些清理工做。

一旦咱們將完成咱們的項目對於異步Servlet示例,項目結構看起來會像下面的圖片:

在監聽中初始化線程池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
packagecom.journaldev.servlet.async;
 
importjava.util.concurrent.ArrayBlockingQueue;
importjava.util.concurrent.ThreadPoolExecutor;
importjava.util.concurrent.TimeUnit;
 
importjavax.servlet.ServletContextEvent;
importjavax.servlet.ServletContextListener;
importjavax.servlet.annotation.WebListener;
 
@WebListener
publicclassAppContextListenerimplementsServletContextListener {
 
    publicvoidcontextInitialized(ServletContextEvent servletContextEvent) {
 
        // create the thread pool
        ThreadPoolExecutor executor =newThreadPoolExecutor(100,200, 50000L,
                TimeUnit.MILLISECONDS,newArrayBlockingQueue<Runnable>(100));
        servletContextEvent.getServletContext().setAttribute("executor",
                executor);
 
    }
 
    publicvoidcontextDestroyed(ServletContextEvent servletContextEvent) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) servletContextEvent
                .getServletContext().getAttribute("executor");
        executor.shutdown();
    }
 
}

實現很直接,若是你不熟悉ThreadPoolExecutor 框架請讀線程池的ThreadPoolExecutor 。關於listeners 的更多細節,請閱讀教程Servlet Listener

工做線程實現

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
packagecom.journaldev.servlet.async;
 
importjava.io.IOException;
importjava.io.PrintWriter;
 
importjavax.servlet.AsyncContext;
 
publicclassAsyncRequestProcessorimplementsRunnable {
 
    privateAsyncContext asyncContext;
    privateintsecs;
 
    publicAsyncRequestProcessor() {
    }
 
    publicAsyncRequestProcessor(AsyncContext asyncCtx,intsecs) {
        this.asyncContext = asyncCtx;
        this.secs = secs;
    }
 
    @Override
    publicvoidrun() {
        System.out.println("Async Supported? "
                + asyncContext.getRequest().isAsyncSupported());
        longProcessing(secs);
        try{
            PrintWriter out = asyncContext.getResponse().getWriter();
            out.write("Processing done for "+ secs +" milliseconds!!");
        }catch(IOException e) {
            e.printStackTrace();
        }
        //complete the processing
        asyncContext.complete();
    }
 
    privatevoidlongProcessing(intsecs) {
        // wait for given time before finishing
        try{
            Thread.sleep(secs);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}

注意:在請求和響應時使用AsyncContext對象,而後在完成時調用 asyncContext.complete() 方法。

AsyncListener 實現

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
packagecom.journaldev.servlet.async;
 
importjava.io.IOException;
importjava.io.PrintWriter;
 
importjavax.servlet.AsyncEvent;
importjavax.servlet.AsyncListener;
importjavax.servlet.ServletResponse;
importjavax.servlet.annotation.WebListener;
 
@WebListener
publicclassAppAsyncListenerimplementsAsyncListener {
 
    @Override
    publicvoidonComplete(AsyncEvent asyncEvent)throwsIOException {
        System.out.println("AppAsyncListener onComplete");
        // we can do resource cleanup activity here
    }
 
    @Override
    publicvoidonError(AsyncEvent asyncEvent)throwsIOException {
        System.out.println("AppAsyncListener onError");
        //we can return error response to client
    }
 
    @Override
    publicvoidonStartAsync(AsyncEvent asyncEvent)throwsIOException {
        System.out.println("AppAsyncListener onStartAsync");
        //we can log the event here
    }
 
    @Override
    publicvoidonTimeout(AsyncEvent asyncEvent)throwsIOException {
        System.out.println("AppAsyncListener onTimeout");
        //we can send appropriate response to client
        ServletResponse response = asyncEvent.getAsyncContext().getResponse();
        PrintWriter out = response.getWriter();
        out.write("TimeOut Error in Processing");
    }
 
}

通知的實如今 Timeout()方法,經過它發送超時響應給客戶端。

Async Servlet 實現

這是咱們的異步Servlet實現,注意使用AsyncContext和ThreadPoolExecutor進行處理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
packagecom.journaldev.servlet.async;
 
importjava.io.IOException;
importjava.util.concurrent.ThreadPoolExecutor;
 
importjavax.servlet.AsyncContext;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
 
@WebServlet(urlPatterns ="/AsyncLongRunningServlet", asyncSupported =true)
publicclassAsyncLongRunningServletextendsHttpServlet {
    privatestaticfinallongserialVersionUID = 1L;
 
    protectedvoiddoGet(HttpServletRequest request,
            HttpServletResponse response)throwsServletException, IOException {
        longstartTime = System.currentTimeMillis();
        System.out.println("AsyncLongRunningServlet Start::Name="
                + Thread.currentThread().getName() +"::ID="
                + Thread.currentThread().getId());
 
        request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED",true);
 
        String time = request.getParameter("time");
        intsecs = Integer.valueOf(time);
        // max 10 seconds
        if(secs >10000)
            secs =10000;
 
        AsyncContext asyncCtx = request.startAsync();
        asyncCtx.addListener(newAppAsyncListener());
        asyncCtx.setTimeout(9000);
 
        ThreadPoolExecutor executor = (ThreadPoolExecutor) request
                .getServletContext().getAttribute("executor");
 
        executor.execute(newAsyncRequestProcessor(asyncCtx, secs));
        longendTime = System.currentTimeMillis();
        System.out.println("AsyncLongRunningServlet End::Name="
                + Thread.currentThread().getName() +"::ID="
                + Thread.currentThread().getId() +"::Time Taken="
                + (endTime - startTime) +" ms.");
    }
 
}

Run Async Servlet

如今,當咱們將上面運行servlet URL:

http://localhost:8080/AsyncServletExample/AsyncLongRunningServlet?time=8000

獲得響應和日誌:

1
2
3
4
AsyncLongRunningServlet Start::Name=http-bio-8080-exec-50::ID=124
AsyncLongRunningServlet End::Name=http-bio-8080-exec-50::ID=124::Time Taken=1 ms.
Async Supported?true
AppAsyncListener onComplete

若是運行時設置time=9999,在客戶端超時之後會獲得響應超時錯誤處理和日誌:

1
2
3
4
5
6
7
8
9
10
11
12
13
AsyncLongRunningServlet Start::Name=http-bio-8080-exec-44::ID=117
AsyncLongRunningServlet End::Name=http-bio-8080-exec-44::ID=117::Time Taken=1 ms.
Async Supported?true
AppAsyncListener onTimeout
AppAsyncListener onError
AppAsyncListener onComplete
Exceptioninthread"pool-5-thread-6"java.lang.IllegalStateException: The request associated with the AsyncContext has already completed processing.
    at org.apache.catalina.core.AsyncContextImpl.check(AsyncContextImpl.java:439)
    at org.apache.catalina.core.AsyncContextImpl.getResponse(AsyncContextImpl.java:197)
    at com.journaldev.servlet.async.AsyncRequestProcessor.run(AsyncRequestProcessor.java:27)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:680)

注意:Servlet線程執行完,很快就和全部主要的處理工做是發生在其餘線程。

相關文章
相關標籤/搜索