Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Data From Redis in batch RedisTemplate

Tags:

java

spring

redis

I am using RedisTemplate in my spring boot application and I am able to read using singleKey.

String valueJson = (String) redisTemplate.opsForValue().get(setKey(someId));

I have now a List of "someId" like "List someIds" and I want to get the data of all Ids. Of course I can iterate on the list and hit redis with indivisual keys, but I dont want that, instead I want provide the whole list to get the response in one go.

Please help.

like image 357
Muhammad Umer Avatar asked Feb 01 '17 08:02

Muhammad Umer


1 Answers

You need to use pipelining: https://redis.io/topics/pipelining

List<Object> results = redisTemplate.executePipelined(
  new RedisCallback<Object>() {
    public Object doInRedis(RedisConnection connection) throws DataAccessException {
      StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
      for(String id:someIds) 
        stringRedisConn.get(id);

    return null;
  }
});

Or in Java 8:

List<Object> results = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
    StringRedisConnection stringRedisConn = (StringRedisConnection) connection;

    someIds.forEach(id -> {
        stringRedisConn.get(id);
    });

    return null;
});

The results List will contain all that you want.

like image 191
Thomas Lehoux Avatar answered Oct 22 '22 05:10

Thomas Lehoux