
package com.ruoyi.common.redis.configure;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.time.Duration;

@Configuration
public class RedisConfigInfo {

    @Value("${spring.redis.host:localhost}")
    private String redisHost;

    @Value("${spring.redis.port:6379}")
    private int redisPort;

    @Value("${spring.redis.timeout:2000ms}")
    private Duration timeout;

    @Value("${spring.redis.password:#{null}}")
    private String password;

    private RedisClient redisClient;
    private ClientResources clientResources;
    private StatefulRedisConnection<String, String> connection;

    @Bean
    public RedisClient redisClient() {
        clientResources = DefaultClientResources.builder().build();

        RedisURI.Builder uriBuilder = RedisURI.Builder
                .redis(redisHost, redisPort)
                .withTimeout(timeout);

        if (password != null && !password.isEmpty()) {
            uriBuilder.withPassword(password.toCharArray());
        }

        RedisURI redisURI = uriBuilder.build();
        redisClient = RedisClient.create(clientResources, redisURI);
        return redisClient;
    }

    @Bean
    public StatefulRedisConnection<String, String> redisConnection(RedisClient redisClient) {
        connection = redisClient.connect();
        return connection;
    }

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

    @PreDestroy
    public void destroy() {
        if (connection != null) {
            connection.close();
        }
        if (redisClient != null) {
            redisClient.shutdown();
        }
        if (clientResources != null) {
            clientResources.shutdown();
        }
    }
}

