java - Java 无法将 reactor.core.publisher.MonoDefer 转换为 EntityClass
问题描述
在这里,我尝试使用返回 PublisherRedisTemplate
的 reactive-redis升级我的 spring-data-redis。ReactiveRedisTemplate
在这种情况下,我想将方法更改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。
推荐阅读
- javascript - Flow中类型和变量之间的名称冲突
- python - 2度多变量曲线拟合
- python - 使用范围参数比较两个数组(大小相同)中值的分布
- javascript - 选择器没有响应 ios React Native
- sql - SQL,哪个命令不会结束事务?
- java - 处理在线游戏中的玩家速度
- haskell - 在haskell中制作Integral类的newtype实例
- javascript - D3.js v5 不使用 d3.tsv() 显示任何数据
- java - 观察者和 getstyleclass() 监听器之间的 Javafx 冲突
- java - 如何使可滚动的 JPanel 显示 JLabels