Servlet中的异步处理

时间:2015-05-01 13:25:42

标签: java servlets asynchronous

我想等待每个请求10秒的请求,但是请求不必互相等待。所以第二个请求不必等待20秒。

我的Servlet:

    @WebServlet(value = "/account", asyncSupported = true)
    public class AccountServlet extends javax.servlet.http.HttpServlet {

        public AccountServlet() {

        }

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) {
            AsyncContext ac = request.startAsync();

            ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
            executor.execute(new MyAsyncService(ac));
        }

        @Override
        public void init(ServletConfig config) throws ServletException {

        }
    }

我的异步流程类:

    class MyAsyncService implements Runnable {

        AsyncContext ac;

        public MyAsyncService(AsyncContext ac) {
            this.ac = ac;
        }

        @Override
        public void run() {
            try {
                System.out.println("started");
                Thread.sleep(10000);
                System.out.println("completed");
                ac.complete();
            } catch (InterruptedException ex) {
                Logger.getLogger(MyAsyncService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

在不阻塞线程的情况下安排完成请求会更加优化。下面是您修改的代码(使用Java 8 lambdas)。

@WebServlet(value = "/account", asyncSupported = true)
public class AccountServlet extends javax.servlet.http.HttpServlet {
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        AsyncContext ac = request.startAsync();
        executor.schedule(ac::complete, 10, TimeUnit.SECONDS);
    }

    @Override
    public void destroy() {
        executor.shutdown();
    }
}

请注意,根据您的运行时环境(即容器),您可能不被允许创建自己的执行程序,并且可能需要使用EE容器提供的执行程序。