Spring mvc send mail as non-blocking

I am developing an application, and this application sends mail in some cases. For instance:

When the user updates his email address, an activation email is sent to the user to verify the new email address. Here is a snippet 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 that response time increases longer due to sending email. Is there a way to send email as a non-blocking method? For example, mail is sent in the background and the code runs.

Thanks in advance

+4
source share
2 answers

You can configure the asynchronous method with Spring to run in a separate thread.

 @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 made assumptions here on your model, but let me say that you can pass all the arguments needed to send this mail. If you configured correctly, this bean will be created as a proxy, and calling the annotated @Async method @Async execute it in another thread.

  @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 

Spring's dock should be enough to help you set it up.

+4
source

Same as above.

But don't forget to include the Async task in the Spring configuration file (example: 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 { } 
-one
source

Source: https://habr.com/ru/post/1495587/


All Articles