package com.tzld.piaoquan.recommend.server.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class UserRedisTemplateConfig {

    @Bean("userRedisPool")
    @ConfigurationProperties(prefix = "spring.user-redis.lettuce.pool")
    public GenericObjectPoolConfig<LettucePoolingClientConfiguration> userRedisPool() {
        return new GenericObjectPoolConfig<>();
    }

    @Bean("userRedisConfig")
    @ConfigurationProperties(prefix = "spring.user-redis")
    public RedisStandaloneConfiguration userRedisConfig() {
        return new RedisStandaloneConfiguration();
    }

    @Bean("userRedisFactory")
    @Primary
    public LettuceConnectionFactory factory(@Qualifier("userRedisPool") GenericObjectPoolConfig<LettucePoolingClientConfiguration> userRedisPool,
                                            @Qualifier("userRedisConfig") RedisStandaloneConfiguration userRedisConfig) {
        LettuceClientConfiguration lettuceClientConfiguration =
                LettucePoolingClientConfiguration.builder().poolConfig(userRedisPool).build();
        return new LettuceConnectionFactory(userRedisConfig, lettuceClientConfiguration);
    }

    @Bean(name = "userRedisTemplate")
    public RedisTemplate<String, String> getRedisTemplate(@Qualifier("userRedisFactory") RedisConnectionFactory factory) {
        return buildRedisTemplateByString(factory);
    }

    /**
     * 构建redisTemplate 使用string序列化
     *
     * @param factory
     * @return
     */
    private RedisTemplate<String, String> buildRedisTemplateByString(RedisConnectionFactory factory) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // key的序列化类型 保证可读性
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

}
