我想在我的新 Spring 应用程序中保持完全的 react 性。因此,我将 web-flux/reactor 和 ReactiveRepository 与 MongoDB 一起使用。
您知道如何将 java-mail 响应式(Reactive)地集成到技术堆栈中吗?任何替代方案?
最佳答案
对于发送电子邮件,仍然是 非阻塞 ,您可以在另一个线程中运行有关发送电子邮件的代码。如果您使用的是 Spring WebFlux,这可以很容易地完成,只需将发送电子邮件的代码包装在以下 的工厂方法中即可。单声道 (一个 Reactor 库发布者)。
Mono.fromCallable()
要么
Mono.fromRunnable()
短代码
Mono.fromCallable(()-> sendEmail())
.subscribe();
其中 sendEmail() 是您发送电子邮件的函数。
这也是文档中推荐的 - How Do I Wrap a Synchronous, Blocking Call?
长码
以下是我在应用程序中使用的完整示例代码 -
Mono.fromCallable(() -> {
try {
MimeMessageHelper helper = new MimeMessageHelper(sender.createMimeMessage());
helper.setTo(to);
helper.setSubject(subject);
helper.setText(body);
sender.send(helper.getMimeMessage());
log.info("Email send successfully, subject {} , to {}", subject, to);
return true;
} catch (Exception e) {
log.warn("Failed to send email with subject {}, due to {}",subject,e.getMessage(), e});
return false;
}
)
.subscribe(result -> log.info("Mail sent {}", result));
当它是响应式(Reactive)堆栈时,永远不要忘记订阅 :D
关于spring-boot - 如何在 spring web-flux 中发送电子邮件 react 性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51091893/