ReactiveRedisOperations not saving object in Redis

489 views Asked by At

I am using ReactiveRedisOperations to save data objects in Redis and this call returns a Mono as per the api. I notice that if I don't do anything with this Mono return than this code does not do anything. Just trying to understand how this works. I would like below code to save every Object to Redis in this loop, however it does not do so, please share what is missing here.

 for (SomeObject obj : list) {
 reactiveRedisOperations.opsForHash().put(key, hashKey, obj).map(b -> obj); }

On the other side if i return the Mono result from similar code via a rest service response than it seems to save in Redis correctly, not sure why this is this way. Thanks

2

There are 2 answers

0
Michael On

This is a quirk of reactive streams, not Lettuce.

Unlike a completable future which begins execution when it's created, a stream won't begin executing (the command isn't sent) until a consumer has subscribed to it.

I believe this is to facilitate backpressure, so a slow consumer isn't flooded with data by the producer.

Some nice reading -> https://blog.knoldus.com/working-with-project-reactor-reactive-streams/

0
tmarwen On

If you return a Mono, to the underlying web framework, which generally will handle subscribe(ing) to this Mono, the respective operation will trigger resulting in whatever side-effects such as data being created in your Redis datastore.

Shall you wish to have your operations executed, you should do the same, i.e. subscribe to the publisher (Mono, or Flux) or return these data wrappers to whatever calling function you would know will handle this for you as in the aforementioned example:

Flux.fromIterable(list)
    .flatMap(obj -> reactiveRedisOperations.opsForHash().put(key, hashKey, obj))
    .subscribe();