2

I need to store a list of object in Redis. Every element of the list should be accessed for a unique key. For that I think that the list of object should be stored as a map of object in Redis (I converted to String before to store it):

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

I used this approach when I implemented it with RedisTemplate (imperative way). Now, I am using Reactive Redis and I would like to know what will be the correct way. I see in Spring Redis exists the ReactiveListOperations interface.

At the moment I have the following code but when I executed, Redis doesn't return any value. I would like if I am using the correct approach to implement it.

@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);
                });
    }
}

Thanks in advance!

Cesar Miguel
  • 661
  • 1
  • 13
  • 38

0 Answers0