每次在值存在时调用 opsForValue().get('id') 时,我都会得到空结果。
我的配置类:
@Configuration
public class CacheConfiguration {
@Bean
public ReactiveRedisOperations<String, Shop> shopRedisOperations(
ReactiveRedisConnectionFactory factory) {
Jackson2JsonRedisSerializer<Shop> serializer = new Jackson2JsonRedisSerializer<>(Shop.class);
RedisSerializationContext.RedisSerializationContextBuilder<String, Shop> builder =
RedisSerializationContext.newSerializationContext(new StringRedisSerializer());
RedisSerializationContext<String, Shop> context = builder.value(serializer).build();
return new ReactiveRedisTemplate<>(factory, context);
}
@Bean
public ReactiveValueOperations<String, Shop> shopCacheValueOps(ReactiveRedisOperations<String, Shop> template) {
return template.opsForValue();
}
}
我的服务等级:
@Service
public class MyService {
private final ReactiveValueOperations<String, Shop> shopsOps;
public Mono<Shop> getShop(String shopId) {
return shopsOps.get(shopId)
.switchIfEmpty(Mono.defer(() -> loadFromDb(shopId)
.doOnNext(shop -> shopsOps.set(shopId, shop).subscribe())
.switchIfEmpty(Mono.error(() -> new NotFoundException()))));
}
}
注意:shopsOps.set(shopId, shop).subscribe()
在 Redis 中正确保存数据但shopsOps.get(shopId)
一直返回空;