Gustavo Gustavo - 1 month ago 7
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:

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


The service where the email is composed:

@Service
public class EmailService {
@Autowired
private EmailClient emailClient;

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

to = "test@domain.com";
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);
emailClient.sendEmail(email);
}
}


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

@RestController
public class EmailController {

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

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

@Service
@Async
public class EmailService 

Do not foget @EnableAsync

Comments