如何将电子邮件服务移动到线程中?
How to move an email service into a thread?
我正在使用 Feign 连接两个微服务。其中一位撰写电子邮件,另一位发送电子邮件。
这是电子邮件客户端:
@FeignClient("holiday-client")
public interface EmailClient {
@RequestMapping(value = "/api/email/sendEmail", method = RequestMethod.POST)
void sendEmail(@RequestBody Email email);
}
撰写电子邮件的服务:
@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);
}
}
以及实际发送电子邮件的其他微服务的控制器:
@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);
}
}
似乎这个 API 被调用了 5 次,直到处理并发送了电子邮件。它有效,因为我收到了 5 封电子邮件,但我也收到了 SocketTimeOutException。
问题是客户端等待电子邮件服务发送邮件的时间太长,我不希望这样。
如何将方法 sendMail 移动到线程中以解决此问题?
在您的服务(或方法)上使用@Async 注释。
@Service
@Async
public class EmailService
不要忘记@EnableAsync
我正在使用 Feign 连接两个微服务。其中一位撰写电子邮件,另一位发送电子邮件。
这是电子邮件客户端:
@FeignClient("holiday-client")
public interface EmailClient {
@RequestMapping(value = "/api/email/sendEmail", method = RequestMethod.POST)
void sendEmail(@RequestBody Email email);
}
撰写电子邮件的服务:
@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);
}
}
以及实际发送电子邮件的其他微服务的控制器:
@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);
}
}
似乎这个 API 被调用了 5 次,直到处理并发送了电子邮件。它有效,因为我收到了 5 封电子邮件,但我也收到了 SocketTimeOutException。 问题是客户端等待电子邮件服务发送邮件的时间太长,我不希望这样。 如何将方法 sendMail 移动到线程中以解决此问题?
在您的服务(或方法)上使用@Async 注释。
@Service
@Async
public class EmailService
不要忘记@EnableAsync