Where can close a Lettuce Redis connection in my Spring Boot application?

Abhii :

I have initialized the Spring Boot app with Lettuce(io.lettuce.core.api) configuration like this

@Configuration
class RedisConfiguration  {

    @Value("${spring.redis.host}")
    private String redisHostname;
    @Value("${spring.redis.port}")
    private int redisPort;

    private StatefulRedisConnection<String, String> redisConnection;
    private static RedisClient redisClient;

    @Bean
    public RedisCommands connectionFactory() {
        RedisURI redisURI = RedisURI.create(redisHostname,redisPort);
        redisClient = RedisClient.create(redisURI);
        redisConnection = redisClient.connect();
        RedisCommands<String, String> syncCommands = 
        redisConnection.sync();
        return syncCommands;
    }
}

I want to call redisClient.shutdown(); when application shuts down or exits. What is the right place to terminate the redis connection ?

mp911de :

You have two options:

  1. Using @PreDestroy:
    @PreDestroy
    public StatefulRedisConnection<String, String> redisConnection() {
        redisConnection.close();
        redisClient.close();
    }
  1. Via @Bean methods

Make sure to expose RedisClient and StatefulRedisConnection as beans. Command interfaces (RedisCommands) do not expose a close() method.

@Configuration
class RedisConfiguration  {

    @Value("${spring.redis.host}")
    private String redisHostname;
    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean(destroyMethod = "close")
    public StatefulRedisConnection<String, String> redisClient() {
        RedisURI redisURI = RedisURI.create(redisHostname,redisPort);
        return RedisClient.create(redisURI);
        redisConnection = redisClient.connect();
    }

    @Bean(destroyMethod = "close")
    public StatefulRedisConnection<String, String> redisConnection(RedisClient client) {
        return client.connect();
    }

    @Bean
    public RedisCommands redisCommands(StatefulRedisConnection<String, String> connection) {
        return connection.sync();
    }
}

The first method is shorter while the @Bean approach lets you interact with intermediate objects in your application.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=100309&siteId=1