如何安全地处理Spring RedisTemplate?

时间:2015-03-02 10:30:26

标签: redis jedis spring-data-redis

我必须根据需要为每个请求(写/读)创建RedisTemplate。 connectionfactory是JedisConnectionFactory

JedisConnectionFactory factory=new 
    JedisConnectionFactory(RedisSentinelConfiguration,JedisPoolConfig);

有一次,我使用RedisTemplate.opsForHash / opsForValue进行操作,如何安全地处理模板,以便将连接返回给JedisPool。

截至目前,我用

执行此操作
template.getConnectionFactory().getConnection().close();

这是正确的方法吗?

1 个答案:

答案 0 :(得分:4)

RedisTemplateRedisConnectionFactory获取连接并声明它已返回到池中,或在命令执行后正确关闭,具体取决于提供的配置。 (见: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;
  }});