springboot + redis 主从怎么配置
时间: 2023-12-08 19:04:20 浏览: 161
首先,你需要在 Spring Boot 项目中添加 Redis 的依赖,可以使用以下 Maven 依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
接着,在 application.properties 或 application.yml 文件中添加 Redis 的配置:
```yaml
# Redis 主节点配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
# Redis 从节点配置
spring.redis.cluster.nodes=192.168.1.1:6379,192.168.1.2:6379
spring.redis.cluster.master=master
```
以上配置是一个 Redis 主节点和两个从节点的示例,其中:
- `spring.redis.host` 和 `spring.redis.port` 是主节点的地址和端口。
- `spring.redis.cluster.nodes` 是从节点的地址和端口列表,多个节点使用英文逗号分隔。
- `spring.redis.cluster.master` 是主节点的名称,可以在 Redis 配置文件中设置。
最后,你需要使用 RedisTemplate 或者 StringRedisTemplate 类来操作 Redis。在 Spring Boot 中,你可以通过注入 RedisTemplate 或者 StringRedisTemplate 类来使用 Redis。例如:
```java
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
```
以上代码中,我们注入了 RedisTemplate 类,并使用其 `opsForValue` 方法来操作 Redis 中的数据。
注意,如果你使用的是 Redis 主从复制模式,你在写入数据时应该使用主节点,而在读取数据时可以使用主节点或从节点。如果你使用的是 Redis 集群模式,Spring Boot 会自动将读取操作负载均衡到不同的节点上。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)