如何在发送servlet响应的同时运行方法,同时还接受进一步的请求?

时间:2017-10-10 03:03:57

标签: java servlets asynchronous

我想要完成的方案如下:

  1. 客户端向servlet提交HTTP POST请求。
  2. servlet向客户端发送响应,确认已收到请求。
  3. 然后,servlet会向系统管理员发送电子邮件通知。
  4. 到目前为止,我能够按照上述顺序完成以下步骤,但最后我遇到了一个问题。如果客户端在电子邮件通知方法EmailUtility.sendNotificationEmail()仍在运行时向同一个或另一个servlet发出另一个HTTP请求,则在完成此电子邮件方法之前,servlet将不再运行任何代码(我正在使用javax.mail如果重要的话发送电子邮件。)

    我曾尝试使用AsyncContext解决此问题(我可能使用不当),但不幸的是问题仍然存在。

    如何使EmailUtility.sendNotificationEmail()在不同的线程/异步运行,以便servlet不必等待此方法完成?

    到目前为止,这是我的代码:

    //Step 1: Client submits POST request to servlet.
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
    
        //Step 2: Servlet sends response to client.
        response.getWriter().write("Your request has been received");
        response.getOutputStream().flush();
        response.getOutputStream().close();
    
        //Step 3: Servlet send email notification.
        final AsyncContext acontext = request.startAsync();
        acontext.start(new Runnable() {
            public void run() {
                EmailUtility.sendNotificationEmail();
                acontext.complete();
            }
        });
    }
    

2 个答案:

答案 0 :(得分:0)

尝试简单的事情,比如线程:

new Thread(new Runnable()
{
   @Override
   public void run()
   {
       EmailUtility.sendNotificationEmail();
   }
}, "Send E-mail").start();

答案 1 :(得分:0)

所以我使用ExecutorService解决了这个问题,如下所示:

ExecutorService executorService = Executors.newFixedThreadPool(10);

executorService.execute(new Runnable() {
    public void run() {
        EmailUtility.sendNotificationEmail();
    }
});

executorService.shutdown();