最近,我们决定在我们的项目中使用spring-webflux和benchbase,我们需要有关如何在反应式编程中解决以下用例的帮助
调用外部服务(我们使用了webclient来调用API。
成功后,
一旦失败,
我们已经编写了一个服务类,并且正在使用两个存储库类将文档保存到沙发上,并使用一个Web客户端来调用外部服务。
我们的服务类方法业务逻辑如下所示。
{
//1. Validate the request and throw the error
List<String> validationMessages = handler.validate(customerRequest);
if (validationMessages != null && !validationMessages.isEmpty()) {
return Mono.error(new InvalidRequestException("Invalid Request", validationMessages, null));
}
//generate the id, set it to the request and save it to BUCKET1
String customerRequestId = sequenceGenerator.nextId(Sequence.CUSTOMER_ACCOUNT_ID);
customerRequest.setcustomerRequestId(customerRequestId);
customerRequestMono = bucket1Repository.save(customerRequest);
//2. Call the external service using webclient
externalServiceResponse = customerRequestWebClient.createCFEEnrollment(customerRequest);
//2. Subscribe to the response and and on Success write audit to BUCKET2 , and onerror write audit to BUCKET2 , and delete the inserted documet from BUCKET1
externalServiceResponse.subscribe(response -> {
//Initialise the success audit bean and save
//2.1 a) Write Audt to BUCKET2
Mono<CustomerAuditBean> auditResponse = bucket2Repository.save(cfeAudit);
}, errorResp -> {
//2.2 a) Write Audt to BUCKET2
//Initialise the error audit bean and save
Mono<CustomerAuditBean> auditResponse = bucket2Repository.save(cfeAudit);
//2.2 b)Delete the inserted
Mono<CustomerRequest> delCustomer = bucket1Repository.deleteByLoanAccountId(loanAccountId);
});
//Get the loan account id and return the same
finalResponse = bucket1Repository.findByCustomerId(customerId);
return Mono.when(externalServiceResponse,customerRequestMono,finalResponse).then(finalResponse)
.doOnSuccess(resp -> {
try {
finalMasterAudit.setServiceResponse(new ObjectMapper().writeValueAsString(resp));
Mono<CustomerAuditBean> auditResponse = bucket2Repository.save(finalMasterAudit);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
})
.doOnError(error -> {
try {
finalMasterAudit.setServiceResponse(new ObjectMapper().writeValueAsString(error.getMessage()));
Mono<CustomerAuditBean> auditResponse = bucket2Repository.save(finalMasterAudit);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
});
}
我们观察到的情侣问题
请帮助我们提供任何提示
答案 0 :(得分:3)
采用上面的代码的一部分:
externalServiceResponse.subscribe(response -> {
Mono<CustomerAuditBean> auditResponse = bucket2Repository.save(cfeAudit);
}, errorResp -> {
Mono<CustomerAuditBean> auditResponse = bucket2Repository.save(cfeAudit);
Mono<CustomerRequest> delCustomer = bucket1Repository.deleteByLoanAccountId(loanAccountId);
});
有两个反应性编程问题:
这样的事情应该可以解决(请原谅,我还没有测试过,所以您可能需要做一些调整):
externalServiceResponse
// If something goes wrong then delete the inserted doc
.onErrorResume(err -> bucket1Repository.deleteByLoanAccountId(loanAccountId))
// Always want to save the audit regardless
.then(bucket2Repository.save(cfeAudit))
.subscribe();
代码中还有其他问题需要解决,例如看来您想要在订阅最终的Mono之前先将Flats映射到多个Monos,但是希望这可以帮助您入门。