1

我需要在 Redis 中存储一个对象列表。应该访问列表的每个元素以获取唯一键。为此,我认为对象列表应该存储为 Redis 中的对象映射(我之前转换为 String 来存储它):

{
      "code1": {
        //object1
      },
      "code2": {
        //object2
      },
      "code3": {
        //object3
      }
      //object n...
    }

当我使用 RedisTemplate (命令式)实现它时,我使用了这种方法。现在,我正在使用 Reactive Redis,我想知道正确的方法是什么。我在 Spring Redis 中看到存在ReactiveListOperations接口。

目前我有以下代码,但是当我执行时,Redis 没有返回任何值。我想如果我使用正确的方法来实现它。

@Service
@RequiredArgsConstructor
public class Service {

    private final Client client;
    private final ReactiveRedisTemplate<String, Map> reactiveRedisTemplate;

    @Override
    public Mono<Element> getElement(String name) {

        return reactiveRedisTemplate.opsForValue().get(Constants.KEY_LIST)
                .switchIfEmpty(Mono.defer(() -> {
                    //I get a map from the service when info is not stored in Redis
                    log.debug("Redis does not contain key: {}", Constants.KEY_LIST);
                    return this.client.getMap()
                            .doOnSuccess(mapFromService -> redisTemplate.opsForValue()
                                    .set(Constants.KEY_LIST, mapFromService));
                }))
                .map(map -> {
                    //I suppose that flow continues here when Redis find the key in Redis
                    log.debug("Map from Redis: {}", map);

                    if (!map.containsKey(name)) {
                        return this.client.getMap()
                                .doOnSuccess(mapFromService -> reactiveRedisTemplate.opsForValue()
                                        .set(Constants.KEY_LIST, mapFromService));
                    }

                    return map;
                }).map(map -> {
                    //I get the specific element from the map
                    return map.get(name);
                });
    }
}

提前致谢!

4

0 回答 0