package com.crunii.micro.component.redis.config;

import com.crunii.micro.component.redis.properties.MicroCacheProperties;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

/**
 * @author 田平 create 2020年1月22日上午10:44:32
 */
@Configuration
@ConditionalOnProperty(name = "spring.redis.password")
@AutoConfigureAfter(RedissonAutoConfiguration.class)
@AutoConfigureBefore(RedisReactiveAutoConfiguration.class)
@EnableConfigurationProperties(value = { MicroCacheProperties.class, CacheProperties.class })
public class RedissonReactorAutoConfiguration {

	@Bean(name = "reactiveRedisTemplate")
	public ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate(RedissonConnectionFactory redissonConnectionFactory,
																	   ResourceLoader resourceLoader) {
		JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(
				resourceLoader.getClassLoader());
		RedisSerializationContext<Object, Object> serializationContext = RedisSerializationContext
				.newSerializationContext().key(jdkSerializer).value(jdkSerializer).hashKey(jdkSerializer)
				.hashValue(jdkSerializer).build();
		return new ReactiveRedisTemplate<>(redissonConnectionFactory, serializationContext);
	}

	@Bean(name = "reactiveStringRedisTemplate")
	public ReactiveStringRedisTemplate reactiveStringRedisTemplate(RedissonConnectionFactory redissonConnectionFactory) {
		return new ReactiveStringRedisTemplate(redissonConnectionFactory);
	}

}
