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 ?
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;
}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With