简体   繁体   中英

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.

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

Same as above.

But remember to enable Async task in Spring configuration file (Ex: 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 {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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