zoukankan      html  css  js  c++  java
  • 59、servlet3.0-异步请求

    59、servlet3.0-异步请求

    59.1 开启servlet异步请求步骤

    1. 支持异步处理 asyncSupported=true
    2. 开启异步模式 req.startAsync();
    3. 业务逻辑进行异步处理;开始异步处理 asyncContext.start()
    4. 获取响应 asyncContext.getResponse()

    59.2 新建异步servlet处理类

    @WebServlet(value = "/async", asyncSupported = true)
    public class HelloAsyncServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            AsyncContext asyncContext = req.startAsync();
            System.out.println("主线程开始:" + Thread.currentThread() + "start..." + System.currentTimeMillis());
            asyncContext.start(() -> {
                try {
                    System.out.println("子线程开始:" + Thread.currentThread() + "start..." + System.currentTimeMillis());
                    sayHello();
                    asyncContext.complete();
                    ServletResponse response = asyncContext.getResponse();
                    response.getWriter().write("异步执行完成");
                    System.out.println("子线程结束:" + Thread.currentThread() + "end..." + System.currentTimeMillis());
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                }
            });
            System.out.println("主线程结束:" + Thread.currentThread() + "end..." + System.currentTimeMillis());
    
        }
    
        public void sayHello() throws InterruptedException {
            System.out.println("主线程运行:" + Thread.currentThread() + "processing..." + System.currentTimeMillis());
            Thread.sleep(3000);
        }
    }
    
    

    59.3 测试用例

  • 相关阅读:
    Job流程:Shuffle详解
    学Python Django学得很迷茫,怎么办?-转自知乎
    URL补充
    创建多对多以及增加示例
    Day20-初识Ajax
    笔记-自己看Day20-待续
    Day20-单表中获取表单数据的3种方式
    Day19内容回顾
    一点疑惑的解释
    python os.path模块常用方法详解
  • 原文地址:https://www.cnblogs.com/Grand-Jon/p/10089377.html
Copyright © 2011-2022 走看看