如何使用Spring Webflux Reactive Java将几个Mono映射到一个对象中



我想知道将几个响应式服务响应映射或合并为一个唯一对象的正确方法或最佳方法。

例如,像这样简单的传统代码:

public UserProfile getUserProfile(String id){
User user = userService.getUser(id);
Messages messages = messageService.getMessagesFromUser(id);
Notifications notifications = notificationService.getNotificationsForUser(id);
return new UserProfile(user, message, notifications);
}

当试图写得更多时;功能类似";使用webflux,它看起来像这样:

public Mono<UserProfile> getUserProfile(String id){
return userService.getUser(id)
.map( user -> {
return messageService.getMessagesFromUser(id)
.map(messages -> {
return notificationService.getNotificationsForUser(id)
.map(notifications -> new UserProfile(user, message, notifications))
}
}
}

就我个人而言,我不喜欢这种";映射步骤";,因为它不是顺序变换。我需要更像并行处理,这真的很容易用CompletableFuture或其他多线程框架和传统的命令式代码实现(不起作用(。

您认为如何改进此实施?这段代码运行良好,但我认为这不是正确的编写方式。在我看来,它看起来很难看,不太容易理解。

编辑!!!我想我已经找到了使用Mono.zip的更好方法,但我认为它应该是可改进的

@GetMapping("v1/event/validate/")
public Mono<PanoramixScoreDetailDTO> validateEvent(@RequestBody LeadEventDTO eventDTO) {
return leadService.getLead(eventDTO.getSiteId(), eventDTO.getIdContacto())
.flatMap(lead -> {
Mono<PhoneValidationDTO> phoneValidation = validationService.validatePhone(eventDTO.getSiteId(), lead.getPhone());
Mono<EmailValidationDTO> emailValidation = validationService.validateEmail(eventDTO.getSiteId(), lead.getLeadUser().getEmail());
Mono<ProcessedProfileSmartleadDTO> smartleadProfile = smartleadService.getProcessedProfile(eventDTO.getSiteId(), eventDTO.getIdUsuario());
return Mono.zip(phoneValidation, emailValidation, smartleadProfile)
.map(tuple -> panoramixScoreMapper.mapTo(lead, tuple.getT1(), tuple.getT2(), tuple.getT3(), eventDTO));
});
}

我想听听你的意见。谢谢

Mono.zip()是一种方法,但您可以通过使用覆盖来保存一个步骤,该覆盖允许您一次性指定压缩发布者和地图功能:

@GetMapping("v1/event/validate/")
public Mono<PanoramixScoreDetailDTO> validateEvent(@RequestBody LeadEventDTO eventDTO) {
return leadService.getLead(eventDTO.getSiteId(), eventDTO.getIdContacto())
.flatMap(lead ->
Mono.zip(arr ->
panoramixScoreMapper.mapTo(lead, (PhoneValidationDTO) arr[0],
(EmailValidationDTO) arr[1],
(ProcessedProfileSmartLeadDTO) arr[2], eventDTO),
validationService.validatePhone(eventDTO.getSiteId(), lead.getPhone()),
validationService.validateEmail(eventDTO.getSiteId(), lead.getLeadUser().getEmail()),
smartleadService.getProcessedProfile(eventDTO.getSiteId(), eventDTO.getIdUsuario()))
);
}

这对我有效。

public Mono<UserProfile> getUserProfile(final String id) {
// TODO
return Mono
.zip(user, messages, notifications)
.map(tuple -> new UserProfile(tuple.getT1(), tuple.getT2(), tuple.getT3()));
}

最新更新