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 FeatureRedisTemplateConfig {

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

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

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

    @Bean(name = "featureRedisTemplate")
    public RedisTemplate<String, String> getFeatureRedisTemplate(@Qualifier("featureRedisFactory") RedisConnectionFactory factory) {
        return buildFeatureRedisTemplateByString(factory);
    }

    private RedisTemplate<String, String> buildFeatureRedisTemplateByString(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;
    }

}
