package com.jeequan.jeepay.agent.config;

import com.jeequan.jeepay.core.cache.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * redis管理类
 *
 * @author terrfly
 *
 * @date 2021-04-27 15:50
 */
@Configuration
public class RedisConfig {

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

    @Value("${spring.redis.port}")
    private Integer port;

    @Value("${spring.redis.timeout}")
    private Integer timeout;

    @Value("${spring.redis.database}")
    private Integer defaultDatabase;

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

    /** 作用：不同系统的前缀。  a.当连接不同的database时可以为空(物理隔离)； b.当redis集群时因为必须同一个database，所以需通过前缀区分不同系统的业务。 **/
    @Value("${spring.redis.sys-prefix-key}")
    private String sysPrefixKey;

    /** 当前系统的redis缓存操作对象 (主对象) **/
    @Primary
    @Bean(name = "defaultStringRedisTemplate")
    public StringRedisTemplate sysStringRedisTemplate() {

        // 赋值前缀key
        RedisUtil.SYS_PREFIX_KEY = sysPrefixKey;

        StringRedisTemplate template = new StringRedisTemplate();

        LettuceConnectionFactory jedisConnectionFactory = new LettuceConnectionFactory();
        jedisConnectionFactory.setHostName(host);
        jedisConnectionFactory.setPort(port);
        jedisConnectionFactory.setTimeout(timeout);

        if (!StringUtils.isEmpty(password)) {
            jedisConnectionFactory.setPassword(password);
        }

        if (defaultDatabase != 0) {
            jedisConnectionFactory.setDatabase(defaultDatabase);
        }

        jedisConnectionFactory.afterPropertiesSet();

        template.setConnectionFactory(jedisConnectionFactory);
        return template;
    }

}
