Servlet开启异步上下文

package com.czy.servlet;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author czy
 *
 */
@WebServlet(urlPatterns={ "/message.do" },loadOnStartup=1,asyncSupported=true)
public class MessageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*String message = request.getParameter("message");
        System.out.println(message);*/
        AsyncContext asyncContext = request.startAsync();
        asyncContext.setTimeout(5000);
        asyncContext.addListener(new AsyncListener() {
        
            @Override
            public void onTimeout(AsyncEvent arg0) throws IOException {
                //异步超时时
            }
        
            @Override
            public void onStartAsync(AsyncEvent arg0) throws IOException {
                //异步开始时
            }
        
            @Override
            public void onError(AsyncEvent arg0) throws IOException {
                //异步错误时
            }
        
            @Override
            public void onComplete(AsyncEvent arg0) throws IOException {
                //异步完成时
            }
        });
        //将耗时间的操作放在异步上下文中执行主要的好处是不影响Tomcat单位时间
        //接入的用户请求的数量,如果没有异步环境Tomcat默认的200个线程用完之后
        //其他用户请求就必须排队等待Tomcat接入,这样越靠后的请求等待时间越长
        //甚至可能半分钟时间都无法正常接入
        //启动异步上下文进行异步接入
        asyncContext.start(() -> {
        
            //ServletRequest req = asyncContext.getRequest();
            //ServletResponse resp = asyncContext.getResponse();
            //执行耗时间的操作
            //耗时间操作完成之后,要么结束异步上下文
            //asyncContext.complete();
            //要么将请求派发到某个页面上
            asyncContext.dispatch("index.jsp");
        
        });
        System.out.println("1234");
    }

}

你可能感兴趣的:(Servlet开启异步上下文)