我想在用户注册后立即发送电子邮件。这是场景:
用户应立即获得成功的注册消息,电子邮件发送过程也应该并行运行,但不应影响注册成功响应。即接受电子邮件延迟,但由于电子邮件处理,注册成功消息响应应该延迟。
答案 0 :(得分:2)
Spring的方法是使用Async service发送电子邮件:
可以在方法上提供@Async注释,以便异步调用该方法。换句话说,调用者将在调用时立即返回,并且该方法的实际执行将发生在已提交给Spring TaskExecutor的任务中。
答案 1 :(得分:0)
如果您不关心事务(即使数据库插入失败也应发送电子邮件),您可以通过示例将执行与执行框架并行化:
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
找到有关并发的更多信息