Redis 如何安全地处置Spring模板?
我必须根据需要为每个请求(写/读)创建一个模板。 连接工厂是绝地连接工厂Redis 如何安全地处置Spring模板?,redis,jedis,spring-data-redis,Redis,Jedis,Spring Data Redis,我必须根据需要为每个请求(写/读)创建一个模板。 连接工厂是绝地连接工厂 JedisConnectionFactory factory=new JedisConnectionFactory(RedisSentinelConfiguration,JedisPoolConfig); 有一次,我使用RedisTemplate.opsForHash/opsForValue执行操作,了解如何安全地处理模板,以便将连接返回到spool 到目前为止,我是用 template.getConnecti
JedisConnectionFactory factory=new
JedisConnectionFactory(RedisSentinelConfiguration,JedisPoolConfig);
有一次,我使用RedisTemplate.opsForHash/opsForValue执行操作,了解如何安全地处理模板,以便将连接返回到spool
到目前为止,我是用
template.getConnectionFactory().getConnection().close();
这是正确的方法吗?
RedisTemplate
从RedisConnectionFactory
获取连接,并断言它已返回到池,或在命令执行后正确关闭,具体取决于提供的配置。(见:)
通过getConnectionFactory().getConnection().close()手动关闭连接
将获取新的连接并立即关闭
因此,如果您想拥有更多的控制权,可以获取连接,执行一些操作,然后关闭它
RedisConnection connection = template.getConnectionFactory().getConnection();
connection... // call ops as required
connection.close();
或者使用RedisTemplate.execute(…)和redistcallback一起执行,这样您就不必担心获取和返回连接了
template.execute(new RedisCallback<Void>() {
@Override
public Void doInRedis(RedisConnection connection) throws DataAccessException {
connection... // call ops as required
return null;
}});
template.execute(new RedisCallback()){
@凌驾
public Void doInRedis(重新连接连接)引发DataAccessException{
连接…//根据需要调用ops
返回null;
}});
我只使用opsForHash/opsfervalue/execute执行操作。所以我没有明确关闭连接?我在从池中获取连接时遇到异常。我想这可能是因为模板没有被正确销毁/处置。现在我没有面临连接问题。我已经按照您的回答删除了线路。