我必须根据需要为每个请求(写入/读取)创建 RedisTemplate。 连接工厂是JedisConnectionFactory
JedisConnectionFactory factory=new
JedisConnectionFactory(RedisSentinelConfiguration,JedisPoolConfig);
有一次,我用RedisTemplate.opsForHash/opsForValue做操作,如何安全地处理模板,让连接返回到JedisPool。
截至目前,我使用
template.getConnectionFactory().getConnection().close();
这是正确的方法吗?
最佳答案
RedisTemplate
从 RedisConnectionFactory
获取连接并断言它返回到池中,或者在命令执行后正确关闭,具体取决于提供的配置。 (参见:JedisConnection#close())
通过 getConnectionFactory().getConnection().close();
手动关闭连接将获取一个新连接并立即关闭它。
所以如果你想有更多的控制权,你可以获取连接,执行一些操作并稍后关闭它
RedisConnection connection = template.getConnectionFactory().getConnection();
connection... // call ops as required
connection.close();
或将 RedisTemplate.execute(...)
与 RedisCallback
一起使用,这样您就不必担心获取和返回连接。
template.execute(new RedisCallback<Void>() {
@Override
public Void doInRedis(RedisConnection connection) throws DataAccessException {
connection... // call ops as required
return null;
}});
关于redis - 如何安全处置Spring RedisTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28807555/