我想要完成的方案如下:
到目前为止,我能够按照上述顺序完成以下步骤,但最后我遇到了一个问题。如果客户端在电子邮件通知方法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();
}
});
}
答案 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();