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.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 序列化hash key
template.setHashKeySerializer(new StringRedisSerializer());
// 序列化hash value
template.setHashValueSerializer(template.getValueSerializer());
// 序列化value
template.setValueSerializer(template.getValueSerializer());
return template;
}
}
这段代码定义了一个配置类RedisConfig
,其中创建了一个RedisTemplate<String, Object>
的Bean实例,并对其进行了基本的配置,包括设置了key和hash key的序列化方式为StringRedisSerializer
。这样可以确保Redis中存储的key不会出现乱码问题。
评论已关闭