简体   繁体   English

将 @Cacheable 注释与 Reactive 控制器方法一起使用

[英]Using @Cacheable annotation with a Reactive controller method

I am currently trying to implement a caching with Redis for Sprint Boot application:我目前正在尝试使用 Redis 为 Sprint Boot 应用程序实现缓存:

@Cacheable(value = "products", key = "#id")
@GetMapping(value = "/product/{id}")
public Mono<Product> getProduct(@PathVariable("id") String sku) {
    ...
}

However, I am encountering this exception:但是,我遇到了这个异常:

java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [reactor.core.publisher.MonoMapFuseable]

Based on my research, this has to do with it trying to serialize the Mono return type, rather than Product itself.根据我的研究,这与它尝试序列化 Mono 返回类型有关,而不是Product本身。 So my question is, for reactive methods such as this, what is the recommended way of implementing a caching mechanism with Redis?所以我的问题是,对于像这样的反应式方法,使用 Redis 实现缓存机制的推荐方法是什么? Comments and feedback would be greatly appreciated.评论和反馈将不胜感激。

Change return type of getProduct() from Mono to Product .将 getProduct() 的返回类型从Mono更改为Product

Since you are getting only one product at a time, and you are using Mono<> because it emits at most one item and then (optionally) terminates with an onComplete signal or an onError signal.由于您一次只获得一种产品,并且您使用 Mono<> 是因为它最多发出一项,然后(可选)以 onComplete 信号或 onError 信号终止。

so instead of that use Product as return type and define if else for no product ie, at error state.因此,而不是使用 Product 作为返回类型,并为没有产品定义 else ,即处于错误状态。

Or else go through these links for ways of implementing a caching mechanism with Redis或者通过这些链接了解使用 Redis 实现缓存机制的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM