【问题标题】:How to dispose Spring RedisTemplate safely?如何安全地处理 Spring RedisTemplate?
【发布时间】:2015-03-02 10:30:25
【问题描述】:

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

JedisConnectionFactory factory=new 
    JedisConnectionFactory(RedisSentinelConfiguration,JedisPoolConfig);

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

到目前为止,我用

template.getConnectionFactory().getConnection().close();

这是正确的方法吗?

【问题讨论】:

    标签: redis jedis spring-data-redis


    【解决方案1】:

    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;
      }});
    

    【讨论】:

    • 我只使用 opsForHash/opsForValue/execute 进行操作。所以我没有明确关闭连接?
    • 我在从池中获取连接时遇到了异常。我认为这可能是因为 RedisTemplate 没有被正确销毁/处置。现在我没有遇到那个连接问题。我已经删除了你回答的线路。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 2012-11-30
    • 2013-08-21
    • 2022-11-10
    • 2013-08-21
    相关资源
    最近更新 更多