即使存在值,也无法单独从 Redis 加载值
Unable to load value from Redis alone even if value is present
我正在使用 Reactive Redis,我试图将 Redis 用作数据库的缓存。我正在检查缓存中是否存在值?如果存在则 return 如果结果返回则查询数据库;存储结果缓存它并 return 它。
但是,即使值存在于 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 中存在值,调用也总是会访问数据库。我在这里做错了什么?
基于 你可以试试 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.
我正在使用 Reactive Redis,我试图将 Redis 用作数据库的缓存。我正在检查缓存中是否存在值?如果存在则 return 如果结果返回则查询数据库;存储结果缓存它并 return 它。
但是,即使值存在于 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 中存在值,调用也总是会访问数据库。我在这里做错了什么?
基于 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.