Search code examples
javaspringspring-bootjedis

Should I always call close of jedis instance at the end of business logic?


I`m using jedis as the with spring boot for redis connection.

The jedis pool is configured as follow:

@Configuration
@ConditionalOnClass(JedisPool.class)
@EnableConfigurationProperties(JedisProperties.class)
public class JedisAutoConfiguration {
    private JedisProperties jedisProperties;
    
    public JedisAutoConfiguration(JedisProperties jedisProperties) {
        this.jedisProperties = jedisProperties;
    }
    
    @Bean
    @ConditionalOnMissingBean(JedisPool.class)
    public JedisPool jedisPool() {
        
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(jedisProperties.getPool().getMaxIdle());
        poolConfig.setMaxTotal(jedisProperties.getPool().getMaxTotal());
        poolConfig.setMaxWaitMillis(jedisProperties.getPool().getMaxWaitMillis() * 1000);
        
        JedisPool jedisPool = new JedisPool(poolConfig, jedisProperties.getHost(), jedisProperties.getPort(),
                jedisProperties.getTimeout()*1000, jedisProperties.getPassword(), 0);
        return jedisPool;
    }
}

Each time when I need to connect to the redis, I would rent a resource from jedis pool:

@Service
public class UserService   {

    
    @Autowired
    private JedisPool jedisPool;


    public User FindUserFromCache(Integer id){
        Jedis resource  = jedisPool.getResource()
        // business logic

        // resource.close()
    }

}

Question:

1.Should I return the resource to pool at the end of business logic? Could spring boot or java runtime handle this situation automatically?

2.If resource not closed then the resource would never return to the pool?


Solution

  • Should I return the resource to pool at the end of business logic?

    Yes.

    You can use Java's try-with-resources feature as well.

        try (Jedis resource  = jedisPool.getResource()) {
            // business logic
        }
    

    Could spring boot or java runtime handle this situation automatically?

    JedisPool is base on Apache commons-pool2 project which neither part of spring (boot) or core java. So these can't/don't handle this situation automatically.

    If resource not closed then the resource would never return to the pool?

    To be precise, if resource is not returned then it would never be back to the pool. There are other ways to return the resource to the pool. But close() supposed to be user-friendly way.