如何安全地处理 Spring RedisTemplate?

Aha*_*a M 5 redis jedis spring-data-redis

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

JedisConnectionFactory factory=new 
    JedisConnectionFactory(RedisSentinelConfiguration,JedisPoolConfig);
Run Code Online (Sandbox Code Playgroud)

有一次,我用RedisTemplate.opsForHash/opsForValue做操作,如何安全的处理模板,让连接返回到JedisPool。

到目前为止,我用

template.getConnectionFactory().getConnection().close();
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?

Chr*_*obl 5

RedisTemplate从 获取连接RedisConnectionFactory并断言它返回到池中,或者在命令执行后正确关闭,具体取决于提供的配置。(见:JedisConnection#close()

通过手动关闭连接getConnectionFactory().getConnection().close();将获取一个新连接并立即关闭它。

所以如果你想有更多的控制权,你可以获取连接,执行一些操作并稍后关闭它

RedisConnection connection = template.getConnectionFactory().getConnection();
connection... // call ops as required
connection.close();
Run Code Online (Sandbox Code Playgroud)

RedisTemplate.execute(...)与 一起使用RedisCallback,这样您就不必担心获取和返回连接。

template.execute(new RedisCallback<Void>() {

  @Override
  public Void doInRedis(RedisConnection connection) throws DataAccessException {
    connection... // call ops as required
    return null;
  }});
Run Code Online (Sandbox Code Playgroud)