Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose Spring RedisTemplate safely?

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 ?

like image 277
Ahamed Mustafa M Avatar asked Mar 02 '15 10:03

Ahamed Mustafa M


1 Answers

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;
  }});
like image 89
Christoph Strobl Avatar answered Sep 30 '22 18:09

Christoph Strobl