package cn.datax.common.redis.config;

import cn.datax.common.redis.service.impl.RedissonLocker;
import cn.datax.common.redis.utils.LockUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@EnableConfigurationProperties({RedisProperties.class})
@AllArgsConstructor
public class RedissonConfig {

    private RedisProperties redisProperties;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        if(redisProperties.getCluster() != null){
            // 集群模式配置
            config.useClusterServers()
                    .addNodeAddress(redisProperties.getCluster().getNodes().stream().toArray(String[]::new))
                    .setPassword(StringUtils.isBlank(redisProperties.getPassword()) ? null : redisProperties.getPassword());
        }else if(redisProperties.getSentinel() != null){
            //添加哨兵配置
            config.useMasterSlaveServers().setMasterAddress(redisProperties.getSentinel().getMaster())
                    .addSlaveAddress(redisProperties.getSentinel().getNodes().stream().toArray(String[]::new))
                    .setPassword(StringUtils.isBlank(redisProperties.getPassword()) ? null : redisProperties.getPassword());
        }else {
            //单节点
            config.useSingleServer().setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
                    .setPassword(StringUtils.isBlank(redisProperties.getPassword()) ? null : redisProperties.getPassword());
        }
        return Redisson.create(config);
    }

    @Bean
    public RedissonLocker redissonLocker(RedissonClient redissonClient) {
        RedissonLocker locker = new RedissonLocker(redissonClient);
        // 设置LockUtil的锁处理对象
        LockUtil.setLocker(locker);
        return locker;
    }
}
