package org.springblade.common.auth;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author caiyihua
 */
@Slf4j
@EnableRedisHttpSession
@Configuration
public class SessionStoreConfig {

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

    @Value("${redis.conn.port}")
    private int redisPort;

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

    @Value("${redis.conn.timeout:5000}")
    private int redisTimeout;

    @Setter
    @Value("${redis.conn.max-total:8}")
    private int poolMaxTotal;
    @Setter
    @Value("${redis.conn.min-idle:0}")
    private int poolMinIdle;
    @Setter
    @Value("${redis.conn.max-idle:8}")
    private int poolMaxIdle;
    @Setter
    @Value("${redis.conn.test-on-borrow:false}")
    private boolean redisTestOnBorrow;

    @Bean
    public JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redisHost);
        factory.setPort(redisPort);
        factory.setPassword(redisPassword);
        factory.setTimeout(redisTimeout);
        factory.setUsePool(true);
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(poolMaxIdle);
        poolConfig.setMaxTotal(poolMaxTotal);
        poolConfig.setMinIdle(poolMinIdle);
        poolConfig.setTestOnBorrow(redisTestOnBorrow);
        factory.setPoolConfig(poolConfig);
        log.info("用于Session的Redis连接池配置为: 最大连接数-{}, 最大空闲连接数-{}", poolMaxTotal, poolMaxIdle);
        return factory;
    }

}