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 ?
You have two options:
@PreDestroy
: @PreDestroy
public StatefulRedisConnection<String, String> redisConnection() {
redisConnection.close();
redisClient.close();
}
@Bean
methodsMake 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.