java - 即使值存在,也无法单独从 Redis 加载值

标签 java reactive-programming spring-data-redis spring-reactive

我正在使用Reactive Redis,我试图使用Redis作为数据库的缓存。我正在检查缓存中是否存在值?如果存在则返回它,否则如果结果返回则查询数据库;存储结果缓存并返回。

但是,即使 Redis 中存在值,它仍然会一直查询数据库。

public Mono<User> getUser(String email) {
    return reactiveRedisOperation.opsForValue().get("tango").switchIfEmpty(
        // Always getting into this block (for breakpoint) :(
        queryDatabase().flatMap(it -> {
            reactiveRedisOperation.opsForValue().set("tango", it, Duration.ofSeconds(3600)).then(Mono.just(it)); 
        })
    );
}

private Mono<User> queryDatabase() {
    return Mono.just(new User(2L,"test","test","test","test","test",true,"test","test","test"));
}

但是即使 Redis 中存在值,调用也始终会访问数据库。我在这里做错了什么?

最佳答案

基于this answer你可以尝试使用Mono.defer:

public Mono<User> getUser(String email) {
    return reactiveRedisOperation.opsForValue().get("tango").switchIfEmpty(Mono.defer(() -> {
        // Always getting into this block (for breakpoint) :(
        queryDatabase().flatMap(it -> {
            reactiveRedisOperation.opsForValue().set("tango", it, Duration.ofSeconds(3600)).then(Mono.just(it)); 
        })})
    );
}

更新:

我对 Mono 没有太多经验。我指出的答案解释了这一点:

... computation was already triggered at the point when we start composing our Mono types. To prevent unwanted computations we can wrap our future into a defered evaluation:

... is trapped in a lazy supplier and is scheduled for execution only when it will be requested.

关于java - 即使值存在,也无法单独从 Redis 加载值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60553715/

相关文章:

java - 如何在不安装Stanford版本的eclipse并使用JRE7的情况下在eclipse中使用karel.jar?

java servlet : better way to do multiple inserts and locking tables?

java - Mono.fromCallable 和 Mono.justOrEmpty 的区别

java - 需要更改什么才能成功将 spring-data-redis 1.8.15 的 XML 配置移动到 2.1.0?

java - 如何 Autowiring RedisTemplate<String,Object>

JavaFX Web View : Transparent WebView keeps old content drawn

java - 自动解决 PMD 违规问题?

ios - KVO 通知间歇性崩溃

reactjs - 找不到模块 'minizlib'

java - 在Redis中更新哈希的单个字段