doOnNext() 不会被称为 Spring Webflux



我是反应式编程和SpringWebflux的新手我有一个从Redis获取一些键的方法,如果这个键为null或不等于指定的字符串,我想抛出一个异常,但嵌套的donOnNext方法不会被调用,customerRepository.save(customer)会被触发,而必须抛出异常并断链。有人能向我解释API反应堆在我的情况下是如何运行的吗?

这是我的方法:

@Override
public Mono<RegistrationVerificationResDTO> verifyCustomerAndGenerateToken(Mono<VerifyOtpReqDTO> verifyOtpReqDTO) {
return verifyOtpReqDTO
.doOnNext(verifyDTO -> reactiveRedisOperations
.opsForValue()
.get(RedisDictionary.OTP_KEY + verifyDTO.getPhoneNumber())
.filter(otp -> otp.equalsIgnoreCase(verifyDTO.getOtp()))
.switchIfEmpty(Mono.error(ForbiddenException::new)))
.map(verifyDTO -> customerRepository.findById(verifyDTO.getId())
.orElseThrow(() -> new NotFoundException("Customer not found")))
.doOnNext(customer -> {
customer.setVerified(true);
customerRepository.save(customer);
})
.map(customer -> new RegistrationVerificationResDTO().setAccessToken("accessToken")
.setRefreshToken("refreshToken")
.setCustomer(customer));
}

更新:我意识到,如果我们在doOnNext方法中创建另一个发布者,因为spring只订阅了最外部的发布者,那么内部的发布者就不会被触发。我已经更新了代码,但它仍然不起作用。

我猜你是说这"不起作用",因为即使对第二个(最里面的(doOnNext进行了(正确的(更改,你也无法观察到DB中保存的customer

第三个doOnNext是有问题的:假设customerRepository是反应库,customerRepository.save(customer)是NO-OP,因为(惰性(Mono既没有附加到主序列,也没有订阅

只需用flatMap替换doOnNext(并用switchIfEmpty保留对最内层doOnNext的更改(,使其成为Spring将订阅的反应链的一部分。

最新更新