3

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
  • 17,546
  • 2
  • 55
  • 95
Abhii
  • 295
  • 2
  • 6
  • 18

1 Answers1

5

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.

mp911de
  • 17,546
  • 2
  • 55
  • 95
  • Is it safe to create a `RedisAdvancedClusterCommands` as a singleton spring bean and share it across multiple service threads? In most examples online, I see `StatefulRedisClusterConnection` being declared as a bean and `RedisAdvancedClusterCommands` being instantiated per service call? However, the fact that the interface is marked as `thread-safe` in the docs and the absence of `RedisTransactionalCommands` or a similar interface from it makes me think it is safe to use across service threads. – 6harat Jan 16 '20 at 11:53