2015-03-02 199 views
3

我需要为每个请求(写/读)创建RedisTemplate。 ConnectionFactory是JedisConnectionFactory如何安全地处理Spring RedisTemplate?

JedisConnectionFactory factory=new 
    JedisConnectionFactory(RedisSentinelConfiguration,JedisPoolConfig); 

有一次,我做操作与RedisTemplate.opsForHash/opsForValue,如何处置模板安全,使连接返回到JedisPool。

截至目前,我这样做与

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

这是正确的方式?

回答

3

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

我只对opsForHash/opsForValue/execute进行操作。所以我没有明确地关闭连接? – 2015-03-03 07:47:29

+0

是的,不需要明确关闭它。 – 2015-03-03 08:21:32

+0

我在从池中获取连接时遇到异常。我认为这可能是因为RedisTemplate没有被正确销毁/处置。现在我没有面对这个连接问题。我已经删除了你已经回答的线路。 – 2015-03-03 09:50:32