I use spring's RedisTemplate.
I have a hash in redis.
I want to query redis, using the template, in order to get all entries whose key in a certain set of keys.
I noticed the method:
Map<Object, Object> entries = redisTemplate.opsForHash().multiGet(HASH_NAME, keySet);
But, unfortunately this method returns only the values, without the matching keys.
I could also do it like this:
Map<Object, Object> entries = redisTemplate.opsForHash().entries(HASH_NAME);
for(Object key : keySet){
System.out.println(entries.get(key));
}
But this means I will get all entries from redis, to my local machine, and iterate them.
Don't I have a better way of doing this?
If you're using RedisTemplate you could use opsForHash().entries(H key)
to get all the hash, (keys and values).
For example...
Map messageGroupMetadata = redisTemplate.opsForHash().entries(H key);
Besides it's necesary to set RedisTemplate serializers to complete this operation.
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
From the documentation of HMGET:
Array reply: list of values associated with the given fields, in the same order as they are requested.
And from the documentation for Spring Redis Hash multiGet, you can see it returns a list (not a map), which should be in the same order as the keys you sent.
Example code:
List<Object> values = redisTemplate.opsForHash().multiGet(HASH_NAME, keySet);
int i = 0;
for (String k: keySet) {
// k is the key
// and here is the value corresponding to the key k
Object value = values.get(i++);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With