package com.aisi.template.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; 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.core.StringRedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * Redis 配置类 * 配置 Redis 序列化方式 * * 主要功能: * 1. RedisTemplate:用于操作对象类型数据 * 2. StringRedisTemplate:用于操作字符串类型数据 * * 序列化配置: * - Key:使用 String 序列化 * - Value:使用 JSON 序列化(支持类型信息) * - HashKey:使用 String 序列化 * - HashValue:使用 JSON 序列化 * * @author Claude * @since 2024-04-09 */ @Configuration public class RedisConfig { /** * 配置 RedisTemplate(用于操作对象) * 步骤: * 1. 创建 RedisTemplate 对象 * 2. 配置 ObjectMapper(支持类型信息) * 3. 配置 Key 序列化方式 * 4. 配置 Value 序列化方式 * * @param factory Redis 连接工厂 * @param objectMapper Jackson ObjectMapper * @return RedisTemplate 对象 */ @Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory, ObjectMapper objectMapper) { // 1. 创建 RedisTemplate 对象 RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(factory); // 2. 配置 ObjectMapper(支持类型信息,用于反序列化时确定类型) ObjectMapper redisMapper = objectMapper.copy(); redisMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); redisMapper.activateDefaultTyping( LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY ); // 3. 配置序列化器 StringRedisSerializer stringSerializer = new StringRedisSerializer(); GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(redisMapper); // 3.1 Key 使用 String 序列化 template.setKeySerializer(stringSerializer); // 3.2 HashKey 使用 String 序列化 template.setHashKeySerializer(stringSerializer); // 3.3 Value 使用 JSON 序列化 template.setValueSerializer(jsonSerializer); // 3.4 HashValue 使用 JSON 序列化 template.setHashValueSerializer(jsonSerializer); // 4. 执行初始化 template.afterPropertiesSet(); return template; } /** * 配置 StringRedisTemplate(用于操作字符串) * 说明: * - StringRedisTemplate 专门用于处理字符串类型数据 * - Key 和 Value 都使用 String 序列化 * - 适用于简单的键值对操作 * * @param factory Redis 连接工厂 * @return StringRedisTemplate 对象 */ @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { return new StringRedisTemplate(factory); } }