java - 在在线应用程序中使用Java Executor服务

标签 java spring-mvc executorservice

我有在线申请的一项功能。我需要在生成收据后将收据邮寄给客户。我的问题是邮件功能需要更多时间近20至30秒,客户在网上交易时无法等待很长时间。

所以我使用java ExecutorService来独立运行邮件服务[sendMail],并将响应页面返回给客户,无论邮件是否发送。

在线应用程序中使用ExecutorService是否正确[Http请求和响应]。下面是我的代码。请多多指教。

@RequestMapping(value="/generateReceipt",method=RequestMethod.GET)
public @ResponseBody ReceiptBean generateReceipt(HttpServletRequest httpRequest,HttpServletResponse httpResponse) {

// Other codes here 
...
...

I need run below line independently, since it takes more time. so commeneted and wrote executor service
//mailService.sendMail(httpRequest,  httpResponse, receiptBean);

java.util.concurrent.ExecutorService executorService = java.util.concurrent.Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
    ReceiptBean receiptBean1;
    public void run() {
        mailService.sendMail(httpRequest,  httpResponse, receiptBean);
    }
    public Runnable init(ReceiptBean receiptBean) {
        this.receiptBean = receiptBean1;
        return(this);
    }
}.init(receiptBean));
executorService.shutdown();

return receiptBean;
} 

最佳答案

你可以做到这一点,尽管我不希望这段代码出现在 Controller 类中,而是出现在单独的(关注点分离和全部)中。

不过,既然你好像用的是Spring,那你不妨用他们的scheduling framework .

关于java - 在在线应用程序中使用Java Executor服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53627130/

相关文章:

java - 我的 QuickSort 实现存在问题

java - 当路径有空间时使用批处理循环构建类路径时出现问题

java - HttpSecurity 配置 - permitall 仍然需要基本身份验证

java - spring 是否负责关闭您的 ExecutorService?

java - linux top 命令的内存和 jconsole 堆的使用有很大不同

java - 如何设置 IntelliJ Java App Engine 项目以使用服务(模块)

java - 谁能帮我理解 Spring 4 在这个例子中是如何工作的?

java - 当我使用 java -jar File.jar 运行 spring-boot 时,没有 ServletContext 资源 [/WEB-INF/layouts/layouts.xml] 的 URL

java - 为什么 SocketTimeoutException 使我的程序卡住?

java - 如何搁浅 executorservice