springboot集成redis集群代码
时间: 2023-07-19 22:19:00 浏览: 167
以下是Spring Boot集成Redis集群的代码示例:
1. 添加Redis依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. application.properties配置
```
# Redis Cluster
spring.redis.cluster.nodes=192.168.0.1:7001,192.168.0.2:7002,192.168.0.3:7003,192.168.0.4:7004,192.168.0.5:7005,192.168.0.6:7006
spring.redis.cluster.max-redirects=3
```
3. Redis Cluster配置类
```
@Configuration
public class RedisConfig {
@Autowired
private Environment env;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(
Arrays.asList(env.getProperty("spring.redis.cluster.nodes").split(",")));
redisClusterConfiguration.setMaxRedirects(Integer.parseInt(env.getProperty("spring.redis.cluster.max-redirects")));
return new JedisConnectionFactory(redisClusterConfiguration);
}
@Bean
public RedisTemplate<?, ?> redisTemplate() {
RedisTemplate<byte[], byte[]> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
return redisTemplate;
}
}
```
4. 在代码中使用RedisTemplate
```
@Autowired
private RedisTemplate<String, Object> redisTemplate;
redisTemplate.opsForValue().set("key", "value");
Object value = redisTemplate.opsForValue().get("key");
```
以上代码示例是Spring Boot集成Redis集群的基本配置,可以根据具体需求进行修改和扩展。
阅读全文