首页 > 解决方案 > Java 无法将 reactor.core.publisher.MonoDefer 转换为 EntityClass

问题描述

在这里,我尝试使用返回 PublisherRedisTemplate的 reactive-redis升级我的 spring-data-redis。ReactiveRedisTemplate在这种情况下,我想将方法​​更改findCacheMono. 问题是使用 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但由于我接受通用,它也不起作用。我应该怎么做,请帮忙。

标签: javaspringrx-javaproject-reactor

解决方案


最好指定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。


推荐阅读