Spring Boot 整合 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);
return template;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
template.setDefaultSerializer(new StringRedisSerializer());
return template;
}
}
这段代码定义了两个Bean,一个是RedisTemplate<String, Object>
类型的Bean,用于操作非字符串类型的key和value,另一个是StringRedisTemplate
类型的Bean,用于操作字符串类型的key和value。这些Bean都设置了默认的序列化器,以确保键值可以正确地序列化和反序列化。
评论已关闭