Spring MVC以非阻塞方式发送邮件

Hüs*_*BAL 5 java email spring-mvc

我正在开发一个应用程序,该应用程序在某些情况下会发送邮件。例如;

当用户更新其电子邮件时,会向用户发送一封激活邮件,以验证新的电子邮件地址。这是一段代码;

............
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;
Run Code Online (Sandbox Code Playgroud)

我的问题是由于发送电子邮件,响应时间变长了。有没有像非阻止方式那样发送电子邮件的方法?例如,邮件发送在后台执行,代码继续运行

提前致谢

Sot*_*lis 6

您可以使用 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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里对您的模型进行了假设,但假设您可以传递该方法发送邮件所需的所有参数。如果设置正确,这个 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
Run Code Online (Sandbox Code Playgroud)

Spring 文档应该足以帮助您进行设置。