Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 836
Hüseyin BABAL Avatar asked Aug 06 '13 18:08

Hüseyin BABAL


1 Answers

You can setup an 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'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.

 @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.

like image 66
Sotirios Delimanolis Avatar answered Sep 28 '22 10:09

Sotirios Delimanolis