2017-10-10 23 views
1

我试图完成情况如下:如何在发送servlet响应之后运行方法,同时还接受进一步的请求?

  1. 客户端提交的HTTP POST请求的servlet。
  2. servlet向客户端发送一个响应,确认已收到请求。
  3. 该小服务程序然后发送电子邮件通知给系统管理员。

到目前为止,我能够按照上述顺序完成以下步骤,但是我在最后遇到了一个问题。如果当电子邮件通知方法EmailUtility.sendNotificationEmail()仍在运行时,客户端向同一个或另一个servlet发出另一个HTTP请求,那么在此电子邮件方法完成之前(我使用javax.mail来发送电子邮件),该servlet将不会运行任何进一步的代码。

我试图用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(); 
     } 
    }); 
} 
+1

在回复请求之前发送电子邮件。它通常是异步的,所以回复将事先收到... –

+0

我曾尝试发送电子邮件预先,但不幸的是,直到电子邮件方法完成,才会发送响应,所以问题仍然存在。 – dat3450

+1

我不认为发送响应后可以使用'AsyncContext';它意味着异步准备响应。 –

回答

0

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

ExecutorService executorService = Executors.newFixedThreadPool(10); 

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

executorService.shutdown(); 
0

尝试简单的东西,比如一个线程:

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

从我的理解,不建议在servlet环境中使用线程。感谢您的帮助。 – dat3450

相关问题