I have written a class where I have connection pool and pipelined and the way to use this class would be something like (i removed a loop, but setKey would be happening in the loop):
private Redis redis = new Redis();
redis.setKey(path, keyValueOutput, 3000);
redis.setKey(path, keyValueOutput, 3000);
redis.setKey(path, keyValueOutput, 3000);
if (redis.getPipelineCount() > 200) {
redis.syncKeys();
System.out.println("200 items added");
}
So as soon as the number of items on pipeline is more than 200 i sync items and clear pipeline and start again. The question is how with this setup correcly return connections back to the pool.
public class Redis {
private JedisPoolConfig poolConfig = new JedisPoolConfig();
private JedisPool jedisPool = new JedisPool(poolConfig,"localhost", 6379);
private Jedis jedis = jedisPool.getResource();
private Pipeline pipeline = jedis.pipelined();
private int pipelineCount = 0;
public void setKey(String path, Map<String, String> keyValueOutput, int expireTime) {
this.pipeline.hset(path, keyValueOutput);
this.pipeline.expire(path, expireTime);
this.pipelineCount = this.pipelineCount + 1;
}
public void syncKeys() {
this.pipeline.sync();
this.pipelineCount = 0;
}
public int getPipelineCount() {
return this.pipelineCount;
}
public void close() {
this.jedis.close();
}
}
As far as I understand I have to wrap jedisPool.getResource() into try block, but I can't put my head around how to combine it with my pipeline and counter together.
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Pipeline p = jedis.pipelined();
p.sync()
} finally {
if (jedis != null) {
jedis.close();
}
}