5

I have to create RedisTemplate for each of the requests (write/read) on demand. The connectionfactory is JedisConnectionFactory

JedisConnectionFactory factory=new 
    JedisConnectionFactory(RedisSentinelConfiguration,JedisPoolConfig);

Once, I do operations with RedisTemplate.opsForHash/opsForValue, how to dispose the templates safely , so that the connection is returned to JedisPool.

As of now , I do this with

template.getConnectionFactory().getConnection().close();

Is this the right way ?

Ahamed Mustafa M
  • 3,069
  • 1
  • 24
  • 34

1 Answers1

5

RedisTemplate fetches the connection from the RedisConnectionFactory and asserts that it is returned to the pool, or closed properly after command execution, depending on the configuration provided. (see: JedisConnection#close())

Closing the connection manually via getConnectionFactory().getConnection().close(); would fetch a fresh connection and close it right away.

So if you want to have a bit more control, you could fetch the connection, perform some operations and close it later

RedisConnection connection = template.getConnectionFactory().getConnection();
connection... // call ops as required
connection.close();

or use RedisTemplate.execute(...) along with RedisCallback, so that you do not have to worry about fetching and returning the connection.

template.execute(new RedisCallback<Void>() {

  @Override
  public Void doInRedis(RedisConnection connection) throws DataAccessException {
    connection... // call ops as required
    return null;
  }});
Christoph Strobl
  • 6,491
  • 25
  • 33
  • 1
    I do operations only with opsForHash/opsForValue/execute. So I dont have explicity close the connection ? – Ahamed Mustafa M Mar 03 '15 at 07:47
  • I was facing exceptions while fetching connections from the pool. I thought it might be because of RedisTemplate not being destroyed /disposed properly. Now I am not facing that connection issue.I have removed the line as you have answered. – Ahamed Mustafa M Mar 03 '15 at 09:50