天天看點

厲害了,Servlet3的異步處理機制

主要增加了以下特性:

1、異步處理支援

2、可插性支援

3、注解支援,零配置,可不用配置web.xml

...

異步處理是什麼鬼?

直接操起鍵盤幹。

@WebServlet(name = "index", urlPatterns = { "/" }, asyncSupported = true)

public class IndexServlet extends HttpServlet {

    @Override

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html");

        try {

            PrintWriter out = resp.getWriter();

            out.println("servlet started.<br/>");

            out.flush();

            AsyncContext asyncContext = req.startAsync();

            asyncContext.addListener(getListener());

            asyncContext.start(new IndexThread(asyncContext));

            out.println("servlet end.<br/>");

            out.flush();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    /**

     * 異步線程結果監聽

     * @author javastack

     * @return

     */

    private AsyncListener getListener() {

        return new AsyncListener() {

            public void onComplete(AsyncEvent asyncEvent) throws IOException {

                asyncEvent.getSuppliedResponse().getWriter().close();

                System.out.println("thread completed.");

            }

            public void onError(AsyncEvent asyncEvent) throws IOException {

                System.out.println("thread error.");

            }

            public void onStartAsync(AsyncEvent asyncEvent) throws IOException {

                System.out.println("thread started.");

            }

            public void onTimeout(AsyncEvent asyncEvent) throws IOException {

                System.out.println("thread timeout.");

            }

        };

    }

}

public class IndexThread implements Runnable {

    private AsyncContext asyncContext;

    public IndexThread(AsyncContext asyncContext) {

        this.asyncContext = asyncContext;

    }

    public void run() {

        try {

            Thread.sleep(5000);

            PrintWriter out = asyncContext.getResponse().getWriter();

            out.println("hello servlet3.<br/>");

            out.flush();

            asyncContext.complete();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}      

通路localhost:8080/test

頁面首先輸出

servlet started.
servlet end.      

過了5秒後再輸出

hello servlet3.      

可以看出servlet立馬傳回了,但沒有關閉響應流,隻是把response響應傳給了線程,線程再繼續輸出,我們可以将比較費資源消耗時間的程式放到異步去做,這樣很大程式上節省了servlet資源。

Springmvc3.2開始也加入了servlet3異步處理這個特性,有興趣的同學可以去研究下。

從上面的servlet注解也可以看出來,servlet3完全解放了web.xml配置,通過注解可以完全代替web.xml配置。

繼續閱讀