java – 返回Mono后的方法调用
作者:互联网
我想在之前返回Mono< Void>时调用该方法:
@Override
public Mono<Void> sendEmail(EmailDto emailDto) {
return mailReactiveClient.sendEmail(message ->
createMessage(emailDto, emailDto.getBody(), message))
.doOnNext(saveNotificationLog(emailDto)); //it's not work
}
private void saveNotificationLog(EmailDto emailDto) {
notificationLogReactiveRepository.save(NotificationLog.builder()
...
.build());
}
方法sendEmailreturns Mono< Void>.
那么如何调用saveNotificationLog?
UPD:让我的问题更简单:
@Override
public Mono<Void> sendEmail(EmailDto emailDto) {
return mailReactiveClient.sendEmail(message ->
createMessage(emailDto, emailDto.getBody(), message))
.doOnNext(System.out.print("Hello world!");
}
如何在sendEmail返回Mono< Void>后调用doOnNextor类似的方法?
解决方法:
doOnNext,通常所有doOn * reactor方法都是副作用方法.您不应该将它们称为执行I / O工作或链操作,而是记录事物而不做任何会影响应用程序状态的事情.
在您的代码示例中,notificationLogReactiveRepository.save返回Mono< Void>. saveNotificationLog返回void,并且不订阅notificationLogReactiveRepository.save返回的发布者.这意味着通知将不会被保存,因为nothing happens until you subscribe.
在这种情况下,似乎你正在尝试连锁操作 – 然后操作符就是为此而做的.您的代码应如下所示:
@Override
public Mono<Void> sendEmail(EmailDto emailDto) {
return mailReactiveClient.sendEmail(message ->
createMessage(emailDto, emailDto.getBody(), message))
.then(saveNotificationLog(emailDto));
}
private Mono<Void> saveNotificationLog(EmailDto emailDto) {
return notificationLogReactiveRepository.save(NotificationLog.builder()
...
.build());
}
标签:project-reactor,spring-webflux,java,reactive-programming 来源: https://codeday.me/bug/20190731/1586881.html