在这里,我尝试使用返回发布者的reactive-redis ReactiveRedisTemplate
来升级我的 spring-data-redis RedisTemplate
。在本例中,我想将方法 findCache
更改为 Mono
。问题是使用 spring-data-redis 的旧 findCache
函数正在接受通用数据,如下所示:
@Autowired
ReactiveRedisTemplate redisTemplate;
public <T> T findCache(String key, Class<T> clazz) {
Object content = this.redisTemplate.opsForValue().get(key);
if (content != null) {
return clazz.cast(content);
}
return null;
}
当然我会得到错误
Cannot cast reactor.core.publisher.MonoDefer to Person
然后,因为我想让它响应式地工作,所以我更新此代码以返回发布者,如下所示:
if (content != null) {
return ((Mono) content).flatMap(o -> clazz.cast(o));
}
但它也不起作用,因为我的 findCache
接受通用。
我需要做什么,请帮忙。
最佳答案
最好指定ReactiveRedisTemplate
参数。但如果不能,您应该将内容类型更改为 Mono<Object>
。像这样的事情:
public <T> Mono<T> findCache(String key, Class<T> clazz) {
@SuppressWarnings("unchecked")
Mono<Object> contentMono = redisTemplate.opsForValue().get(key);
return contentMono.map(clazz::cast);
}
如果缓存不包含给定键的值,它将返回空 Mono,而不是 null。
关于Java 无法将reactor.core.publisher.MonoDefer 转换为EntityClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53680717/