JavaWeb [Basics] servelet asynchronous operation


In actual work, we will encounter some time-consuming operations. At this time, if the response is not timely, it will return failure. If you want to perform asynchronous operations and return data with a delay, you can use the following methods


Use asyncSupported = trueannotations

@WebServlet(name = "apitest", asyncSupported = true)

If you don’t use this annotation, an error will be reported during access

\Users\ASUS\AppData\Roaming\Typora\typora-user-images\image-20200718221455649.png

The following is the source code

@WebServlet(name = "apitest", asyncSupported = true)
public class apitest extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		        doGet(request,response);
    }



    private volatile ExecutorService executorService;

    @Override
    public void init() throws ServletException {
    
    

        super.init();
        //newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
        executorService = Executors.newFixedThreadPool(100);
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        AsyncContext asyncCtx = request.startAsync();
        executorService.submit(new Runnable() {
    
    
            @Override
            public void run() {
    
    
				//延时5秒 ,模拟耗时操作
                try {
    
    
                    Thread.sleep (5000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
				
                PrintWriter writer = null;
                try {
    
    
                    writer = asyncCtx.getResponse().getWriter();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
                //返回数据
                writer.println("servlevt异步处理成功");
                writer.flush();//记得关闭

                asyncCtx.complete();//记得关闭

            }
        }, asyncCtx);

    }
}

Restart tomcat, access the interface /apitest, you can see that after waiting for 5 seconds, the servlevt asynchronous processing success is returned. thread.sleep(), this is generally not needed, and time-consuming operations can be written in actual applications.

Guess you like

Origin blog.csdn.net/qq_31254489/article/details/107603597