package com.lovecoding.redis.redisdemo;

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory( redisConnectionFactory );

        //设置KEY 序列化使用 String 字符串
        redisTemplate.setKeySerializer( RedisSerializer.string() );
        redisTemplate.setHashKeySerializer( RedisSerializer.string() );

        GenericJackson2JsonRedisSerializer jsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();

        //设置 value 序列化为 JSON格式
        redisTemplate.setValueSerializer( jsonRedisSerializer );
        redisTemplate.setHashValueSerializer( jsonRedisSerializer );

        return redisTemplate;
    }

}
