Search code examples
javaredispipelinejedisttl

Redis pipeline usage


I'm trying to understand how pipeline works nad want to try something different. I've noticed that there's no method for setting expire key if the key doesn't have any so I made an example for that with Jedis.

Example

Map<String, Response> responses = new HashMap<>();

long start = System.currentTimeMillis();
try (Jedis resource = redisManager.getResource()) {

    Pipeline pipeline = resource.pipelined();

    responses.put("time", pipeline.ttl(args[1]));

    pipeline.sync();

    pipeline.multi();

    if (responses.get("time").get().equals(-1L)) {
        pipeline.expire(args[1], 15);
    }

    pipeline.exec();

}

I'd like to know that should I use like that or do you have any idea about it? I couldn't find any solution for that.


Solution

  • If you sync and get the result after sending each command to the pipeline then there isn't much difference to sending the commands without pipelining. The benefit of pipelining comes from sending a number of commands without waiting on their responses and then reading the responses back all at once (thus eliminating a lot of time which would have been spent waiting for responses. More info: https://redis.io/topics/pipelining).

    So a more "pipeline-y" implementation of what you have above would look like this (please pardon any mistakes with the exact pipeline method names, I mostly use Spring Data rather than straight Jedis):

    List<String> keysToCheckForTtl = ...
    Map<String, Response> responses = new HashMap<>();
    
    for (String key : keysToCheckForTtl) {
      responses.put(key, pipeline.ttl(key));
    }
    
    pipeline.sync(); // get the responses back for all TTL commands
    
    for (String key : keysToCheckForTtl) {
      if (responses.get(key).get().equals(-1L)) {
            pipeline.expire(key, 15);
      }
    }
    
    pipeline.exec(); // finalize all expire commands
    

    As you can see, this works with a list of keys to check and expire. If you only need to check and then expire a single key, you don't need a pipeline.