package com.imooc.config;

import org.redisson.api.RedissonClient;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@ConditionalOnClass(RedissonClient.class)
public class RedisConfig {

	private static final RedisSerializer<String> STRING_SERIALIZER = new StringRedisSerializer();

	@Bean
	RedissonConnectionFactory redisConnectionFactory(RedissonClient redisson) {
		log.info("------------->>>配置自定义RedissonConnectionFactory");
		return new RedissonConnectionFactory(redisson);
	}

	@Bean
	RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		log.info("------------->>>配置自定义RedisTemplate");
		return buildRedisTemplate(redisConnectionFactory);
	}

	/**
	 * 配置redisTemplate
	 * 
	 * @param redisConnectionFactory
	 * @param enableTransactionSupport
	 * @return
	 */
	private RedisTemplate<String, Object> buildRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		// 配置redisTemplate
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		// key序列化
		redisTemplate.setKeySerializer(STRING_SERIALIZER);
		// value序列化
		redisTemplate.setValueSerializer(STRING_SERIALIZER);
		// Hash key序列化
		redisTemplate.setHashKeySerializer(STRING_SERIALIZER);
		// Hash value序列化
		redisTemplate.setHashValueSerializer(STRING_SERIALIZER);
		// 初始化RedisTemplate
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}
}
