美文网首页
4.1、异步servlet

4.1、异步servlet

作者: lesline | 来源:发表于2018-10-15 09:41 被阅读11次

    同步:接收到一个请求后,tomcat 容器提供一个线程,线程调用servlet。
    异步:请求异步处理后tomcat servlet线程立刻返回,自已启动的线程执行,这样tomcat可以有较大的吞吐量。对前台来说还是同步。

    @WebServlet(asyncSupported = true, urlPatterns = { "/AsyncServlet" })
    public class AsyncServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        public AsyncServlet() {
            super();
        }
        protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
            long t1 = System.currentTimeMillis();
            // 开启异步
            AsyncContext asyncContext = request.startAsync();
            // 执行业务代码
            CompletableFuture.runAsync(() -> doSomeThing(asyncContext,
                    asyncContext.getRequest(), asyncContext.getResponse()));
            System.out.println("async use:" + (System.currentTimeMillis() - t1));
        }
    
        private void doSomeThing(AsyncContext asyncContext, ServletRequest servletRequest, ServletResponse servletResponse) {
                // 模拟耗时操作
                TimeUnit.SECONDS.sleep(5);
                servletResponse.getWriter().append("done");
    
                // 业务代码处理完毕, 通知结束
                asyncContext.complete();
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    代码:
    git@github.com:lesline/servlet.git

    相关文章

      网友评论

          本文标题:4.1、异步servlet

          本文链接:https://www.haomeiwen.com/subject/oewxzftx.html