spring redis 主从集群配置
时间: 2023-11-20 10:57:45 浏览: 108
以下是Spring Boot集成Redis主从集群的配置方法:
1.在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2.在application.properties文件中添加以下配置:
```properties
# Redis主节点配置
spring.redis.master.host=127.0.0.1
spring.redis.master.port=6379
spring.redis.master.password=123456
# Redis从节点配置
spring.redis.slave.nodes=127.0.0.1:6380,127.0.0.1:6381
spring.redis.slave.password=123456
```
3.创建RedisConfig类,配置RedisTemplate和JedisConnectionFactory:
```java
@Configuration
public class RedisConfig {
@Value("${spring.redis.master.host}")
private String masterHost;
@Value("${spring.redis.master.port}")
private int masterPort;
@Value("${spring.redis.master.password}")
private String masterPassword;
@Value("${spring.redis.slave.nodes}")
private String slaveNodes;
@Value("${spring.redis.slave.password}")
private String slavePassword;
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
.master("mymaster")
.sentinel("127.0.0.1", 26379)
.sentinel("127.0.0.1", 26380)
.sentinel("127.0.0.1", 26381)
.setPassword(masterPassword);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfig);
jedisConnectionFactory.setUsePool(true);
jedisConnectionFactory.setPoolConfig(jedisPoolConfig());
return jedisConnectionFactory;
}
@Bean
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(100);
jedisPoolConfig.setMaxIdle(50);
jedisPoolConfig.setMinIdle(20);
jedisPoolConfig.setMaxWaitMillis(3000);
return jedisPoolConfig;
}
}
```
4.在需要使用Redis的类中注入RedisTemplate即可使用。
阅读全文