我想在用户注册后立即发送电子邮件。下面是这种情况:Spring MVC:并行发送响应和方法执行
- 用户将提交报名表格
- 春季控制器将接受请求,将数据插入到数据库,发送电子邮件给用户。
事情是用户应该马上得到成功的注册消息,电子邮件发送过程也应该并行运行,但不应该影响注册成功响应。即接受电子邮件延迟,但注册成功消息响应应该由于电子邮件过程而延迟。
我想在用户注册后立即发送电子邮件。下面是这种情况:Spring MVC:并行发送响应和方法执行
事情是用户应该马上得到成功的注册消息,电子邮件发送过程也应该并行运行,但不应该影响注册成功响应。即接受电子邮件延迟,但注册成功消息响应应该由于电子邮件过程而延迟。
Spring的方式做到这一点是使用一个Async service发送电子邮件:
的@Async注释可以提供一个方法,这样的方法是调用将异步发生。换句话说,调用者将在调用时立即返回,并且方法的实际执行将发生在已提交给Spring TaskExecutor的任务中。
如果你不关心交易(即使数据库插入失败了email发送)可以通过例如并行与执行框架执行:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new DbInsertRunnable());
executor.execute(new EmailSendingRunnable());
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
executor.awaitTermination();
你可以找到更多关于并发这里http://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html
如果要发送一千封电子邮件,它会是一个好方法吗? – manish
为什么不呢? –
它是否为每个请求创建单独的线程?如果它不那么认为它是开销 – manish