1.哨兵集群搭建

		IP						Port				Role
192.168.127.101					27001				Sentinel
192.168.127.101					27002				Sentinel
192.168.127.101					27003				Sentinel

192.168.127.101					7001				Master
192.168.127.101					7002				slave
192.168.127.101					7003				slave

修改配置文件 redis.conf

bind 192.168.127.101
port 7001
replicaof 192.168.127.101 7001
daemonize no
dir "/opt/study/redis/7001"

操作指令

mkdir 7001 7002 7003
-- 修改7001(7002.7003同理)
cp redis.conf 7001/
cd  7001/
vi  redis.conf

修改配置文件sentinel.conf

port 27001
pidfile "/opt/study/redis/27001/redis-sentinel.pid"
sentinel announce-ip "192.168.127.101"
dir "/opt/study/redis/27001"

sentinel monitor mymaster 192.168.127.101 7001 2

操作指令

mkdir 27001 27002 27003
cp sentinel.conf 27001/
cd 27001/
vi sentinel.conf

启动指令

启动redis集群
redis-server ../../7001/redis.conf
redis-server ../../7002/redis.conf
redis-server ../../7003/redis.conf

启动哨兵集群
redis-sentinel ../../27001/sentinel.conf
redis-sentinel ../../27002/sentinel.conf
redis-sentinel ../../27003/sentinel.conf

哨兵集群
在这里插入图片描述redis集群
在这里插入图片描述
故障转移:
在这里插入图片描述

2. RedisTemplate连接哨兵集群

2.1 引入pom依赖

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

2.2 配置文件

spring:
  redis:
    sentinel:
      nodes:
      - 192.168.127.101:27001
      - 192.168.127.101:27002
      - 192.168.127.101:27003
      master: mymaster

在这里插入图片描述

2.3 修改配置类 实现读写分离

  @Bean
    public LettuceClientConfigurationBuilderCustomizer lettuceClientConfigurationBuilderCustomizer(){
        return clientConfigurationBuilder -> clientConfigurationBuilder.readFrom(ReadFrom.REPLICA_PREFERRED);
    }

2.4 测试

测试controller

@RestController
public class RedisController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/set/{key}/{value}")
    public String setKey(@PathVariable("key") String key, @PathVariable("value") String value){
        stringRedisTemplate.opsForValue().set(key, value);
        return "success";
    }

    @GetMapping("/get/{key}")
    public String getKey(@PathVariable("key")String key) {
        String value = stringRedisTemplate.opsForValue().get(key);
        return value;
    }
}

设置值:
在这里插入图片描述

读取值:
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐