简体   繁体   English

Spring mvc发送邮件为非阻塞

[英]Spring mvc send mail as non-blocking

I am developing an application and that application sends mail in some cases. 我正在开发一个应用程序,该应用程序在某些情况下发送邮件。 For example; 例如;

When user updates his email, an activation mail sent to user in order to validate new email address. 当用户更新其电子邮件时,会向用户发送激活邮件以验证新的电子邮件地址。 Here is a piece of code; 这是一段代码;

............
if (!user.getEmail().equals(email)) {
            user.setEmailTemp(email);
            Map map = new HashMap();
            map.put("name", user.getName() + " " + user.getSurname());
            map.put("url", "http://activationLink");
            mailService.sendMail(map, "email-activation");
        }
return view;

My problem is response time gets longer because of email sending. 我的问题是由于电子邮件发送,响应时间变长了。 Is there any way to send email like non-blocking way? 有没有办法像非阻塞方式发送电子邮件? For example, Mail sending executes at background and code running continues 例如,邮件发送在后台执行,代码继续运行

Thanks in advance 提前致谢

You can setup an asynchronous method with Spring to run in a separate thread. 您可以使用Spring设置异步方法以在单独的线程中运行。

@Service
public class EmailAsyncService {
    ...
    @Autowired
    private MailService mailService;

    @Async
    public void sendEmail(User user, String email) {
        if (!user.getEmail().equals(email)) {
            user.setEmailTemp(email);
            Map map = new HashMap();
            map.put("name", user.getName() + " " + user.getSurname());
            map.put("url", "http://activationLink");
            mailService.sendMail(map, "email-activation");
        }
    }
}

I've made assumptions here on your model, but let's say you could pass all the arguments needed for the method to send your mail. 我已经在你的模型上做了假设,但是假设你可以传递方法发送邮件所需的所有参数。 If you set it up correctly, this bean will be created as a proxy and calling the @Async annotated method will execute it in a different thread. 如果你正确设置它,这个bean将被创建为一个代理,并且调用@Async注释的方法将在另一个线程中执行它。

 @Autowired
 private EmailAsyncService asyncService;

 ... // ex: in controller
 asyncService.sendEmail(user, email); // the code in this method will be executed in a separate thread (you're calling it on a proxy)
 return view; // returns right away

The Spring doc should be enough to help you set it up. Spring文档应该足以帮助您进行设置。

Same as above. 与上述相同。

But remember to enable Async task in Spring configuration file (Ex: applicationContext.xml): 但请记住在Spring配置文件中启用Async任务(例如:applicationContext.xml):

<!-- Enable asynchronous task -->
<task:executor id="commonExecutor" pool-size="10"  />
<task:annotation-driven executor="commonExecutor"/>

Or configuration class: 或者配置类:

@Configuration
@EnableAsync
public class AppConfig {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM