springboot应用程序中的哪里可以关闭Redis连接(莴苣)?

时间:2019-05-30 19:36:15

标签: spring spring-boot jedis spring-data-redis lettuce

我已经用这样的一个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连接的正确位置是什么?

1 个答案:

答案 0 :(得分:2)

您有两个选择:

  1. 使用@PreDestroy
    @PreDestroy
    public StatefulRedisConnection<String, String> redisConnection() {
        redisConnection.close();
        redisClient.close();
    }
  1. 通过@Bean方法

确保将RedisClientStatefulRedisConnection公开为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方法则允许您与应用程序中的中间对象进行交互。