cachera
cachera

Reputation: 1

how to fill Map<Object,Object> from Flux<Map.Entry<Object, Object>>,use reactiveRedisTemplate

Flux<Map.Entry<Object, Object>> entries = reactiveRedisTemplate .opsForHash().entries(key);
Map<Object, Object> stringObjectMap = new LinkedHashMap<>();
entries.subscribe(e -> stringObjectMap.put(e.getKey(), e.getValue()));

I want to fill stringObjectMap from entries,but stringObjectMap is always empty.

Upvotes: 0

Views: 3991

Answers (2)

dragos.triteanu
dragos.triteanu

Reputation: 81

I was facing the same problem a couple of days ago, and ended up using the collectMap operation. My use case required that I extract a Processor object from redis, which was stored as hashes, so for doing this, I found out that i can use the following :

operations.opsForHash().entries("processor") // Returns a list of Entry<String,String>

The list of entries will have to be collected as to a map, so that it can be mapped to an object, using the ObjectMapper. The following lambda chain extracts all the hashes from the "processor" key, maps them as a map using collectMap and then using the .map() function, converts this map into a Processor object.

        Mono<Processor> processor = operations.opsForHash()
                                        .entries("processor")
                                        .collectMap(Entry::getKey,Entry::getValue)
                                        .map(entryMap -> new ObjectMapper().convertValue(entryMap, Processor.class));

Upvotes: 2

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

Are you sure that you accounted for the fact that everything is asynchronous?

In this case, the subscribe method doesn't block until the map has been filled but instead returns control immediately. If your next line of code checks the map's content, it might simply be empty because the async operation hasn't completed yet.

Note that there is a collectMap operator that produces a Map reactively (and you can even provide a Supplier<Map> to force a LinkedHashMap instance). Here if you subscribe twice in a row, your map will be shared between the two subscriptions which will both attempt to fill it (which might lead to synchronization issues)...

Upvotes: 0

Related Questions