spring数据redis中存储对象列表的正确方法

bvpmtnay  于 2021-06-09  发布在  Redis
关注(0)|答案(0)|浏览(244)

我需要在redis中存储一个对象列表。列表中的每个元素都应该访问一个唯一的键。为此,我认为object列表应该存储为redis中object的Map(之前我转换成string来存储它):

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

我在用redistemplate(命令式方式)实现它时使用了这种方法。现在,我正在使用Reactredis,我想知道什么是正确的方法。我看到在Spring里存在着 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);
                });
    }
}

提前谢谢!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题