【发布时间】:2021-06-27 12:38:22
【问题描述】:
我目前面临一个关于在 switchIfEmpty 函数中保存 redis 的问题。可能与我在反应式编程方面相当新的事实有关,不幸的是我很难找到合适的例子。
但是我已经能够解决它,但我很确定有更好的方法来解决它。 这是我现在写的:
public Mono<ResponseEntity<BaseResponse<Content>>> getContent(final String contentId, final String contentType){
return redisRepository.findByKeyAndId(REDIS_KEY_CONTENT, contentId.toString()).cast(Content.class)
.map(contentDTO -> ResponseEntity.status(HttpStatus.OK.value())
.body(new BaseResponse<>(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), contentDTO)))
//here I have to defer, otherwise It would never wait for the findByKeyAndId
.switchIfEmpty(Mono.defer(() -> {
Mono<ResponseEntity<BaseResponse<Content>>> responseMono = contentService.getContentByIdAndType(contentId, contentType);
//so far I understood I need to consume every stream I have, in order to actually carry out the task otherwise will be there waiting for a consumer.
//once I get what I need from the cmsService I need to put it in cache and till now this is the only way I've been able to do it
responseMono.filter(response -> response.getStatusCodeValue() == HttpStatus.OK.value())
.flatMap(contentResponse -> redisRepository.save(REDIS_KEY_CONTENT, contentId.toString(), contentResponse.getBody().getData()))
.subscribe();
//then I return the Object I firstly retrived thru the cmsService
return responseMono;
}
));
}
有什么更好的方法的线索或建议吗? 提前感谢您的帮助!
【问题讨论】:
-
如果理解正确,你想从redis中获取,如果没有找到你想从另一个服务中获取值,将它保存在缓存中,然后构建你的响应并返回它。
-
@Toerktumlare 正确!我知道代码很乱,但在某种程度上它执行了整个流程。
标签: java reactive-programming spring-webflux