gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:06:11 24 4
gpt4 key购买 nike

我正在使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com