推荐项目:Spring Boot Distributed Redisson - 实现分布式解决方案
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服务器的host和port
}
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
// 设置key的序列化器
template.setKeySerializer(new StringRedisSerializer());
// 设置hash的key和value的序列化器
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
这个配置类提供了一个基本的LettuceConnectionFactory实例,并配置了一个RedisTemplate实例,该实例使用了Jackson2JsonRedisSerializer来序列化对象,并使用StringRedisSerializer作为key的序列化器。这个配置可以作为开发分布式Redis解决方案的基础。
评论已关闭