【Redis优化】SpringDataRedis序列化方式对比
在Spring Data Redis中,我们可以通过配置来选择不同的序列化方式,以下是几种常见的序列化方式及其对应的配置方法:
- 使用Jackson2JsonRedisSerializer进行JSON格式的序列化:
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
template.setDefaultSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
- 使用StringRedisSerializer进行字符串序列化:
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setDefaultSerializer(stringRedisSerializer);
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(stringRedisSerializer);
template.afterPropertiesSet();
return template;
}
- 使用JdkSerializationRedisSerializer进行Java对象的序列化:
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
template.setDefaultSerializer(jdkSerializationRedisSerializer);
template.setKeySerializer(jdkSerializationRedisSerializer);
template.setValueSerializer(jdkSerializationRedisSerializer);
template.setHashKeySerializer(jdkSerializationRedisSerializer);
template.setHashValueSerializer(jdkSerializationRedisSerializer);
template.afterPropertiesSet();
return template;
}
在选择序列化方式时,需要考虑序列化
评论已关闭