【redis】Spring之RedisTemplate配置与使用
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(); // 默认连接本地Redis实例
}
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
// 设定key的序列化方式
template.setKeySerializer(new StringRedisSerializer());
// 设定hash的key的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
return template;
}
}
这段代码定义了一个配置类RedisConfig
,其中包含了redisConnectionFactory
和redisTemplate
两个Bean的定义。redisConnectionFactory
创建了一个连接到本地Redis实例的LettuceConnectionFactory
。redisTemplate
使用了GenericJackson2JsonRedisSerializer
来序列化对象,并使用StringRedisSerializer
来序列化字符串。这样,我们就可以在Spring应用中方便地使用RedisTemplate
来操作Redis了。
评论已关闭