Jackson 2.x 系列【29】Spring Boot 集成之 Redis 序列化/反序列化
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory, ObjectMapper objectMapper) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
serializer.setObjectMapper(objectMapper);
template.setDefaultSerializer(serializer);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
template.setHashValueSerializer(serializer);
return template;
}
}
这段代码定义了一个配置类,其中创建了一个RedisTemplate
实例,并配置了默认的序列化方式为Jackson2JsonRedisSerializer
,同时设置了键和哈希键的序列化方式为StringRedisSerializer
,值和哈希值的序列化方式也是Jackson2JsonRedisSerializer
。这样,我们就可以在Spring Boot应用中使用Redis并利用Jackson 2进行对象的序列化和反序列化。
评论已关闭