package com.zksy.common.core.redis.redisson;


import com.zksy.common.core.redis.redisson.properties.RedissonProperties;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

/**
 * @author ：BIN.LI
 * @date ：2022/4/15 11:06
 * @description：
 */
@Configuration
@ConditionalOnClass(Config.class) // org.redisson.config.Config
@EnableConfigurationProperties(RedissonProperties.class) // 自定义redisson配置类
public class RedissonAutoConfiguration {
    @Autowired
    private RedissonProperties redissonProperties;

    /**
     * 单机模式自动装配
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(name = "spring.redisson.address")
    RedissonClient redissonSingleClient() {
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress("redis://" + redissonProperties.getAddress())
                .setTimeout(redissonProperties.getTimeout())
                .setConnectionPoolSize(redissonProperties.getConnectionPoolSize())
                .setConnectionMinimumIdleSize(redissonProperties.getConnectionMinimumIdleSize())
                .setPingConnectionInterval(1000)
                .setDatabase(redissonProperties.getDatabase());
        if (!ObjectUtils.isEmpty(redissonProperties.getPassword())) {
            serverConfig.setPassword(redissonProperties.getPassword());
        }
        return Redisson.create(config);
    }

    /**
     * 装配locker类，并将实例注入到 RedissLockUtil 中
     *
     * @return
     */
    @Bean
    DistributedLocker distributedLocker(RedissonClient redissonClient) {
        RedissonDistributedLocker locker = new RedissonDistributedLocker(redissonClient);
        RedissonLockUtil.setLocker(locker);
        return locker;
    }
}
