我已经用这样的一个lettuce(io.lettuce.core.api)配置初始化了springboot应用程序
@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;
}
}
我想在应用程序关闭或退出时调用redisClient.shutdown();
。终止Redis连接的正确位置是什么?
答案 0 :(得分:2)
您有两个选择:
@PreDestroy
: @PreDestroy
public StatefulRedisConnection<String, String> redisConnection() {
redisConnection.close();
redisClient.close();
}
@Bean
方法确保将RedisClient
和StatefulRedisConnection
公开为bean。命令界面(RedisCommands
)不公开close()
方法。
@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();
}
}
第一种方法简短一些,而@Bean
方法则允许您与应用程序中的中间对象进行交互。