Gustavo Gustavo - 1 year ago 101
Java Question

How to move an email service into a thread?

I am using Feign to connect two microservices. One of them composes the email and the other one sends it.

This is the Email Client:

public interface EmailClient {
@RequestMapping(value = "/api/email/sendEmail", method = RequestMethod.POST)
void sendEmail(@RequestBody Email email);

The service where the email is composed:

public class EmailService {
private EmailClient emailClient;

public void sendEmailForNewCampaign() {
String to, subject, body;

to = "";
subject = "A new campaign has started";
body = "This email has the purpose to inform you that a new campaign has been started. Please start your own performance reviews until it ends.";
Email email = new Email(to, subject, body);

And the controller from the other microservice which actually sends the email:

public class EmailController {

private EmailSender emailSender;

@RequestMapping(value = "/api/email/sendEmail", method = RequestMethod.POST)
public ResponseEntity sendEmail(@RequestBody Email email) {
System.out.println(email); //printed 5 times
emailSender.sendMail(email.getTo(), email.getSubject(), email.getBody());
return new ResponseEntity(HttpStatus.ACCEPTED);

It seems that this API is called 5 times until the email is processed and sent. It works cause I receive 5 emails, but I also got a SocketTimeOutException.
The problem is that the client waits too long for the email service to send the mail and I don't want that.
How can I move the method sendMail into a thread in order to solve this problem ?

Answer Source

Use @Async annotation on your service (or method).

public class EmailService 

Do not foget @EnableAsync

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download