我使用的是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));
})})
);
}