SpringBoot教程 | SpringBoot之集成Redis
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.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置template的序列化方式
template.setDefaultSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
// 设置key的序列化方式
template.setKeySerializer(new StringRedisSerializer());
// 设置hash的key的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
// 设置value的序列化方式
template.setValueSerializer(new StringRedisSerializer());
// 设置hash的value的序列化方式
template.setHashValueSerializer(new StringRedisSerializer());
return template;
}
}
这个配置类提供了两个Bean,一个是RedisTemplate<String, Object>
用于序列化和反序列化更复杂的对象,另一个是StringRedisTemplate
用于处理字符串类型的键值对。这里使用了Jackson2JsonRedisSerializer
来进行序列化,并对ObjectMapper
进行了配置,以确保能够正确处理复杂对象类型。同时,为了确保键和值都是以字符串的形式存储,我们设置了相应的序列化器。这样,我们就能够在Spring Boot应用中更加高效地使用Redis了。
评论已关闭