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

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

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

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

    @Bean(name = "midRedisTemplate")
    public RedisTemplate<String, String> getRedisTemplate(@Qualifier("midRedisFactory") 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;
    }

}
