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.setValueSerializer(new StringRedisSerializer());
// 序列化hash value
template.setHashValueSerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
这段代码展示了如何在Spring Boot项目中配置RedisTemplate以便使用RedisConnectionFactory来创建Redis连接,并且使用StringRedisSerializer来序列化和反序列化Redis的key和value。这是一个常见的需求,对于开发者来说,这样的配置能够保证与Redis交互的数据是可读的字符串。