2020-10-25 Redis

作业 1024

1、RDB和AOF的优缺点

# RDB 模式优点
1.RDB快照保存了某个时间点的数据,可以通过脚本执行redis指令'bgsave(非阻塞,后台执行)'或者'save(会阻塞写操作,不推荐)命令自定义时间点'进行备份,可以保留多个备份。
当出现问题'可以恢复到不同时间点的版本',很适合备份,并且此'文件格式支持许多第三方工具',可以进行后续的数据分析

2.RDB可以'最大化Redis的性能',父进程在保存 RDB文件时唯一要做的就是fork出一个子进程,然后这个子进程就会处理接下来的所有保存工作,父进程无须执行任何磁盘 I/O 操作。

3.RDB在大量数据,比如几个G的数据,'恢复的速度比AOF的快

# RDB 模式缺点
1.'不能实时保存数据',可能会丢失自上一次执行RDB备份到当前的内存数据

2.当数据量非常大的时候,从父进程fork子进程进行保存至RDB文件时需要一点时间,取决于磁盘IO性能
'在数据集比较庞大时,fork()生成子进程可能会非常耗时,造成服务器在一定时间内停止处理客户端﹔如果数据集非常巨大,并且CPU时间非常紧张的话,那么这种停止时间甚至可能会长达整整一秒或更久。'
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
# AOF模式优点
1.'数据安全性相对较高',根据所使用的fsync策略(fsync是同步内存中redis所有已经修改的文件到存储设备),默认是appendfsync everysec,即每秒执行一次 fsync,在这种配置下,Redis 仍然可以保持良好的性能,并且就算发生故障停机,也'最多只会丢失一秒钟的数据( fsync会在后台线程执行,所以主线程可以继续努力地处理命令请求)

2.由于该机制对日志文件的写入操作采用的是append模式,因此在写入过程中不需要seek, '即使出现宕机现象,也不会破坏日志文件中已经存在的内容'。然而如果本次操作只是写入了一半数据就出现了系统崩溃问题,不用担心,在Redis下一次启动之前,可以通过 redis-check-aof 工具来解决数据一致性的问题

3.Redis可以'在 AOF文件体积变得过大时,自动地在后台对AOF进行重写',重写后的新AOF文件包含了恢复当前数据集所需的最小命令集合。   整个重写操作是绝对安全的,因为Redis在创建新 AOF文件的过程中,append模式不断的将修改数据追加到现有的 AOF文件里面,即使重写过程中发生停机,现有的 AOF文件也不会丢失。   而一旦新AOF文件创建完毕,Redis就会从旧AOF文件切换到新AOF文件,并开始对新AOF文件进行追加操作。

4.AOF包含一个'格式清晰、易于理解的日志文件'用于记录所有的修改操作。事实上,也可以通过该文件完成数据的重建
AOF文件有序地保存了对数据库执行的所有写入操作,这些写入操作以Redis协议的格式保存,因此 'AOF文件的内容非常容易被人读懂,对文件进行分析(parse)也很轻松'。   
'导出(export)AOF文件也非常简单':举个例子,如果你不小心执行了FLUSHALL.命令,但只要AOF文件未被重写,那么只要停止服务器,移除 AOF文件末尾的FLUSHAL命令,并重启Redis ,就可以将数据集恢复到FLUSHALL执行之前的状态。

# AOF模式缺点
1.即使有些操作是重复的也会全部记录,AOF 的文件大小要大于 RDB 格式的文件
2.AOF 在恢复大数据集时的速度比 RDB 的恢复速度要慢
3.根据fsync策略不同,AOF速度可能会慢于RDB
4.bug 出现的可能性更多

2、master和slave同步过程

1)从服务器连接主服务器,发送PSYNC命令
2)主服务器接收到PSYNC命令后,开始执行BGSAVE命令生成RDB快照文件,并使用缓冲区记录此后执行的所有写命令
3)主服务器BGSAVE执行完后,向所有从服务器发送RDB快照文件,并在发送期间继续记录被执行的写命令
4)从服务器收到快照文件后丢弃所有旧数据,载入收到的快照至内存
5)主服务器快照发送完毕后,开始向从服务器发送缓冲区中的写命令
6)从服务器完成对快照的载入,开始接收命令请求,并执行来自主服务器缓冲区的写命令
7)后期同步,从服务器会先发送自己的slave_repl_offset位置,只同步新增加的数据,不再全量同步

3、哨兵的使用和实现机制?

1 哨兵的准备:先实现主从复制架构

在已实现主从架构的情况下,实现一个一主两从、基于哨兵的高可用redis架构

# 注意: master 的配置文件中masterauth 和slave 都必须相同!!!
==========================================================
# 实现一主二从:
1.所有节点执行:
yum -y install redis
sed -i -e 's/bind 127.0.0.1/bind 0.0.0.0/' -e 's/^# masterauth.*/masterauth 123456/' -e 's/^# requirepass .*/requirepass 123456/' /etc/redis.conf

2.在两台从节点执行:
echo "replicaof 10.0.0.8 6379" >> /etc/redis.conf

3.所有节点执行:
systemctl enable --now redis

# 检查主节点状态
[root@CentOS8 ~]#redis-cli -a 123456 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:2
slave0:ip=10.0.0.58,port=6379,state=online,offset=112,lag=1
slave1:ip=10.0.0.68,port=6379,state=online,offset=112,lag=1
master_replid:3293d562bd15ecac07eecae47100ca67d0c0353c
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:112
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:112

# 配置从节点(两台相同操作):
[root@centos8 ~]#redis-cli -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:6379> REPLICAOF 10.0.0.8 6379
OK Already connected to specified master
127.0.0.1:6379> config set masterauth "123456"
OK
127.0.0.1:6379> info replication
# Replication
role:slave
master_host:10.0.0.8
master_port:6379
master_link_status:up
......
==========================================================

2 编辑哨兵的配置文件

Sentinel实际上是一个特殊的redis服务器,默认监听在26379/tcp端口

哨兵可以不和Redis服务器部署在一起,但一般部署在一起,所有redis节点使用相同的配置文件

# 如果是编译安装,在源码目录有sentinel.conf,复制到安装目录即可
如:/apps/redis/etc/sentinel.conf
==========================================================
# 配置文件:
[root@CentOS8 ~]#grep  '^[^#]' /etc/redis-sentinel.conf 
port 26379
daemonize no
pidfile /var/run/redis-sentinel.pid
logfile ""      # 自定义日志目录,若指定,需要修改权限属性(保持原状,不影响下面生效)
dir /tmp
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 30000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 180000
sentinel deny-scripts-reconfig yes
logfile /var/log/redis/sentinel.log     # 默认日志位置!!!
==========================================================
'必要设置项1'
sentinel monitor mymaster 10.0.0.8 6379 2 
# 指定当前mymaster集群中master服务器的地址和端口
# 2 为法定人数限制(quorum),即有几个sentinel认为master down了就进行故障转移,一般此值是所有sentinel节点数量(一般总数是3以上的奇数)的一半以上的整数值。。。比如,此例中总数是3,即3/2=1.5,取整为2。是master的ODOWN客观下线的依据

'必要设置项2'
sentinel auth-pass mymaster 123456 
# mymaster集群中master的密码。。。注意此行要紧接在上面行的下面!!!


sentinel down-after-milliseconds mymaster 30000 
# (SDOWN)判断mymaster集群中所有节点的主观下线的时间,单位:毫秒,建议3000

sentinel parallel-syncs mymaster 1 
# 发生故障转移后,同时向新master同步数据的slave数量,数字越小总同步时间越长,但可以减轻新master的负载压力

sentinel failover-timeout mymaster 180000 
# 所有slaves指向新的master所需的超时时间,单位:毫秒

# 日志
logfile /var/log/redis/sentinel.log
========================================================================
## 三个哨兵服务器的配置都如下(只有3行需要变动):
========================================================================
sentinel monitor mymaster 10.0.0.8 6379 2         # 修改此行
sed -ri 's/^(sentinel monitor mymaster).*/\1 10.0.0.8 6379 2/' /etc/redis-sentinel.conf
sentinel auth-pass mymaster 123456                # 增加此行(紧跟着上一行)
sed -ri '/sentinel monitor mymaster/a\sentinel auth-pass mymaster 123456' /etc/redis-sentinel.conf
sentinel down-after-milliseconds mymaster 3000    # 修改此行
sed -ri 's/^(sentinel down-after-milliseconds).*/\1 mymaster 3000/' /etc/redis-sentinel.conf

# 最终结果:
[root@centos8 ~]#grep  '^[^#]' /etc/redis-sentinel.conf
port 26379
daemonize no
pidfile /var/run/redis-sentinel.pid
logfile ""
dir /tmp
sentinel monitor mymaster 10.0.0.8 6379 2
sentinel auth-pass mymaster 123456
sentinel down-after-milliseconds mymaster 3000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 180000
sentinel deny-scripts-reconfig yes
logfile /var/log/redis/sentinel.log

3 启动哨兵

# 启动哨兵,在其配置文件中会生成 'sentinel myid'
注:'sentinel myid'是自动生成的,且必须唯一
    若发生雷同需要手动修改,随便改,修改后需重启redis和sentinel服务
==============================================================
# 启动
systemctl enable --now redis-sentinel

# 检查 myid(确保每个哨兵主机myid不同)
[root@CentOS8 ~]#grep 'myid' /etc/redis-sentinel.conf
sentinel myid 482ea8aa1764314909473803ae4e15c93fd9f174
[root@centos8 ~]#grep 'myid' /etc/redis-sentinel.conf
sentinel myid 757ac9a40542a060b12e4f570e9f19c016b0762f
[root@centos8 ~]#grep 'myid' /etc/redis-sentinel.conf
sentinel myid b8f9d69a8b849fa09ede20a45fb8d91c55d72c52


注:如果是编译安装,在所有哨兵服务器执行下面操作启动哨兵
`/apps/redis/bin/redis-sentinel  /apps/redis/etc/sentinel.conf

4 验证哨兵端口

[root@CentOS8 ~]#ss -ntl | grep 26379
LISTEN   0         128                 0.0.0.0:26379            0.0.0.0:*       
LISTEN   0         128                    [::]:26379               [::]:* 

5 查看哨兵日志

# master的哨兵日志
[root@CentOS8 ~]#tail -f /var/log/redis/sentinel.log
19131:X 23 Oct 2020 20:36:12.035 # Configuration loaded
19131:X 23 Oct 2020 20:36:12.035 * supervised by systemd, will signal readiness
19131:X 23 Oct 2020 20:36:12.036 * Running mode=sentinel, port=26379.
19131:X 23 Oct 2020 20:36:12.036 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
19131:X 23 Oct 2020 20:36:12.036 # Sentinel ID is 482ea8aa1764314909473803ae4e15c93fd9f174
19131:X 23 Oct 2020 20:36:12.036 # +monitor master mymaster 10.0.0.8 6379 quorum 2
19131:X 23 Oct 2020 20:36:12.040 * +slave slave 10.0.0.68:6379 10.0.0.68 6379 @ mymaster 10.0.0.8 6379
19131:X 23 Oct 2020 20:36:12.040 * +slave slave 10.0.0.58:6379 10.0.0.58 6379 @ mymaster 10.0.0.8 6379
19131:X 23 Oct 2020 20:36:14.104 * +sentinel sentinel 757ac9a40542a060b12e4f570e9f19c016b0762f 10.0.0.58 26379 @ mymaster 10.0.0.8 6379
19131:X 23 Oct 2020 20:36:14.119 * +sentinel sentinel b8f9d69a8b849fa09ede20a45fb8d91c55d72c52 10.0.0.68 26379 @ mymaster 10.0.0.8 6379


# slave的哨兵日志
[root@centos8 ~]#tail -f /var/log/redis/sentinel.log
18272:X 23 Oct 2020 20:36:12.063 # Configuration loaded
18272:X 23 Oct 2020 20:36:12.063 * supervised by systemd, will signal readiness
18272:X 23 Oct 2020 20:36:12.064 * Running mode=sentinel, port=26379.
18272:X 23 Oct 2020 20:36:12.064 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
18272:X 23 Oct 2020 20:36:12.065 # Sentinel ID is b8f9d69a8b849fa09ede20a45fb8d91c55d72c52
18272:X 23 Oct 2020 20:36:12.065 # +monitor master mymaster 10.0.0.8 6379 quorum 2
18272:X 23 Oct 2020 20:36:12.066 * +slave slave 10.0.0.68:6379 10.0.0.68 6379 @ mymaster 10.0.0.8 6379
18272:X 23 Oct 2020 20:36:12.067 * +slave slave 10.0.0.58:6379 10.0.0.58 6379 @ mymaster 10.0.0.8 6379
18272:X 23 Oct 2020 20:36:14.068 * +sentinel sentinel 482ea8aa1764314909473803ae4e15c93fd9f174 10.0.0.8 26379 @ mymaster 10.0.0.8 6379
18272:X 23 Oct 2020 20:36:14.107 * +sentinel sentinel 757ac9a40542a060b12e4f570e9f19c016b0762f 10.0.0.58 26379 @ mymaster 10.0.0.8 6379

6 当前sentinel状态

# 关注sentinel状态最后一行,涉及到masterIP是多少,有几个slave,有几个sentinels,必须是符合全部服务器数量
# 注意:
'redis-cli -p 26379' 表示连接哨兵服务器!!!!!!!
==========================================================================
# 主节点:
[root@CentOS8 ~]#redis-cli -p 26379 info sentinel
# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=mymaster,status=ok,address=10.0.0.8:6379,slaves=2,sentinels=3

# 任选从节点:
[root@centos8 ~]#redis-cli -p 26379 info sentinel
# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=mymaster,status=ok,address=10.0.0.8:6379,slaves=2,sentinels=3
'两个slave、三个sentinel服务器。。如果sentinels值不符合,检查myid,很可能是因为myid冲突

7 停止Redis Master,测试故障转移

# 杀掉主节点的 redis
killall redis-server

# 查看从节点哨兵信息
[root@centos8 ~]#redis-cli -p 26379 info sentinel
# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=mymaster,status=ok,address=10.0.0.68:6379,slaves=2,sentinels=3
'虽然数量无变化。。因为旧master已经被哨兵修改为一个新的slave!!!
'注意:此处数目并不表示在线!!!!只能表示当前架构各个主机数量!!!(旧master的redis已经切断)

# 查看日志 ,发现新主为 10.0.0.68
18272:X 23 Oct 2020 20:48:21.878 # -odown master mymaster 10.0.0.8 6379     【客观宕机】
18272:X 23 Oct 2020 20:48:21.878 # +failover-end master mymaster 10.0.0.8 6379
18272:X 23 Oct 2020 20:48:21.878 # +switch-master mymaster 10.0.0.8 6379 10.0.0.68 6379【切换新主】
18272:X 23 Oct 2020 20:48:21.878 * +slave slave 10.0.0.58:6379 10.0.0.58 6379 @ mymaster 10.0.0.68 6379
18272:X 23 Oct 2020 20:48:21.879 * +slave slave 10.0.0.8:6379 10.0.0.8 6379 @ mymaster 10.0.0.68 6379
18272:X 23 Oct 2020 20:48:24.911 # +sdown slave 10.0.0.8:6379 10.0.0.8 6379 @ mymaster 10.0.0.68 6379

# 检查主从关系
# 在slave-58查看:
[root@centos8 ~]#redis-cli -a 123456 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:slave
master_host:10.0.0.68
master_port:6379
master_link_status:up
.....
# 在slave-68查看:(已成为新主,且只有一个slave在线)
[root@centos8 ~]#redis-cli -a 123456 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:1
slave0:ip=10.0.0.58,port=6379,state=online,offset=270422,lag=1
master_replid:70c2be922ed56af27eedbd848b2a66c7f7e9a414
.....
============================================================================
# 恢复故障的原master重新加入redis集群
# 重启旧主的 redis
systemctl start redis

# 在新主查看主从关系(等待几秒)
[root@centos8 ~]#redis-cli -a 123456 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:2   # 已有两个slave(哨兵起作用)
slave0:ip=10.0.0.58,port=6379,state=online,offset=286079,lag=0
slave1:ip=10.0.0.8,port=6379,state=online,offset=285946,lag=0
.........

8 故障转移后的redis配置文件会被自动修改

# 故障转移后,redis.conf中的replicaof行的master IP会被修改
# 哨兵配置文件的sentinel monitor IP 同样也会被修改

# 在slave-58查看:
[root@centos8 ~]#grep ^replicaof /etc/redis.conf
replicaof 10.0.0.68 6379

# 在所有节点查看:
[root@centos8 ~]#grep "^sentinel monitor" /etc/redis-sentinel.conf
sentinel monitor mymaster 10.0.0.68 6379 2
'当前监控都为 10.0.0.68 (因为哨兵监控主节点,此时68为新主)

4、redis cluster集群创建和使用

基于Redis 5redis cluster 部署:

1 创建redis cluster集群的环境准备

1. 每个redis 节点采用相同的'硬件配置'、相同的密码、相同的redis版本
2. 所有redis服务器必须没有任何数据
3. 准备六台主机,地址如下
10.0.0.8
10.0.0.18
10.0.0.28
10.0.0.38
10.0.0.48
10.0.0.58

2 启用redis cluster配置

# 安装
dnf -y install redis

# 每个节点修改redis配置,必须开启cluster功能的参数
sed -i.bak -e 's/bind 127.0.0.1/bind 0.0.0.0/' -e '/masterauth/a masterauth 123456' -e '/# requirepass/a requirepass 123456' -e '/# cluster-enabled yes/a cluster-enabled yes' -e '/# cluster-config-file nodes-6379.conf/a cluster-config-file nodes-6379.conf' -e '/cluster-require-full-coverage yes/c cluster-require-full-coverage no' /etc/redis.conf
systemctl enable --now redis

# 验证当前Redis服务状态:
[root@CentOS8 ~]#ss -ntl | grep 6379
LISTEN   0         128                 0.0.0.0:16379            0.0.0.0:*       
LISTEN   0         128                 0.0.0.0:6379             0.0.0.0:*  

注:cluster的端口号是在 redis服务设置的端口号上 +10000 (若修改redis—port=6666,则cluster-port=16666)

3 创建集群

# 注:选项 --cluster-replicas 1 表示每个master对应一个slave节点
===============================================================
# 执行(--cluster create)
[root@CentOS8 ~]#redis-cli -a 123456 --cluster create 10.0.0.8:6379 10.0.0.18:6379 10.0.0.28:6379 10.0.0.38:6379 10.0.0.48:6379 10.0.0.58:6379 --cluster-replicas 1
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
>>> Performing hash slots allocation on 6 nodes...
Master[0] -> Slots 0 - 5460
Master[1] -> Slots 5461 - 10922
Master[2] -> Slots 10923 - 16383
Adding replica 10.0.0.38:6379 to 10.0.0.8:6379
Adding replica 10.0.0.48:6379 to 10.0.0.18:6379
Adding replica 10.0.0.58:6379 to 10.0.0.28:6379
'注: M 表示 master、 S 表示 slave
M: bfbbb2390cffddbdb6cad159658a4b8770702cd8 10.0.0.8:6379
   slots:[0-5460] (5461 slots) master   # 当前master的槽位范围
M: 4457771149df7949b7d94cec318f4e783b5e5a18 10.0.0.18:6379
   slots:[5461-10922] (5462 slots) master
M: 6061cf2702a7c07bb64debbdc9bc7897a672d152 10.0.0.28:6379
   slots:[10923-16383] (5461 slots) master
S: bb1c85f4a072be2d8645a40ecef76c358da29f3b 10.0.0.38:6379
   replicates bfbbb2390cffddbdb6cad159658a4b8770702cd8
S: 5a469424de6187f662ff825b40b3766fca893325 10.0.0.48:6379
   replicates 4457771149df7949b7d94cec318f4e783b5e5a18
S: 7a19f3c4082136d3d7c11f6a5c7665e461b2b565 10.0.0.58:6379
   replicates 6061cf2702a7c07bb64debbdc9bc7897a672d152
Can I set the above configuration? (type 'yes' to accept):      # 输入 yes 自动创建集群
>>> Nodes configuration updated
>>> Assign a different config epoch to each node
>>> Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join
...
>>> Performing Cluster Check (using node 10.0.0.8:6379)
M: bfbbb2390cffddbdb6cad159658a4b8770702cd8 10.0.0.8:6379
   slots:[0-5460] (5461 slots) master  # 已经分配的槽位
   1 additional replica(s)             # 分配了一个slave
M: 4457771149df7949b7d94cec318f4e783b5e5a18 10.0.0.18:6379
   slots:[5461-10922] (5462 slots) master
   1 additional replica(s)
S: bb1c85f4a072be2d8645a40ecef76c358da29f3b 10.0.0.38:6379
   slots: (0 slots) slave          # slave没有分配槽位
   replicates bfbbb2390cffddbdb6cad159658a4b8770702cd8  # 38对应的master=8,此即为8的id
S: 5a469424de6187f662ff825b40b3766fca893325 10.0.0.48:6379
   slots: (0 slots) slave
   replicates 4457771149df7949b7d94cec318f4e783b5e5a18  # 48对应的master=18,此即为18的id
M: 6061cf2702a7c07bb64debbdc9bc7897a672d152 10.0.0.28:6379
   slots:[10923-16383] (5461 slots) master
   1 additional replica(s)
S: 7a19f3c4082136d3d7c11f6a5c7665e461b2b565 10.0.0.58:6379
   slots: (0 slots) slave
   replicates 6061cf2702a7c07bb64debbdc9bc7897a672d152  # 58对应的master=28,此即为28的id
[OK] All nodes agree about slots configuration.
>>> Check for open slots...     # 检查打开的槽位
>>> Check slots coverage...     # 检查插槽覆盖范围
[OK] All 16384 slots covered.   # 所有槽位(16384个)分配完成

# 分析以上结果,可以看到3组master/slave
master:10.0.0.8---slave:10.0.0.38
master:10.0.0.18---slave:10.0.0.48
master:10.0.0.28---slave:10.0.0.58

4 查看主从状态

# master=8
[root@CentOS8 ~]#redis-cli -a 123456 -c info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:1
slave0:ip=10.0.0.38,port=6379,state=online,offset=2282,lag=1
master_replid:284b5af60073a1569904dad89cab418d636d918d
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:2282
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:2282

# master=18
[root@centos8 ~]#redis-cli -a 123456 -c info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:1
slave0:ip=10.0.0.48,port=6379,state=online,offset=2338,lag=0
master_replid:d12f0146815127bb80a434cd4a48269cc166dbf1
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:2338
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:2338

# master=28
[root@centos8 ~]#redis-cli -a 123456 -c info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:1
slave0:ip=10.0.0.58,port=6379,state=online,offset=2380,lag=0
master_replid:fb09a9c75fe74e4e98e43333ce61b9dcee8f56e4
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:2380
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:2380
===============================================================
# slave=48(任取一个)
[root@centos8 ~]#redis-cli -a 123456 -c info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:slave
master_host:10.0.0.18
master_port:6379
master_link_status:up
master_last_io_seconds_ago:6
master_sync_in_progress:0
slave_repl_offset:2464
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:d12f0146815127bb80a434cd4a48269cc166dbf1
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:2464
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:2464
===============================================================
===============================================================
# 所有[节点id] 以及node对应关系
[root@centos8 ~]#redis-cli -a 123456 cluster nodes
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
4457771149df7949b7d94cec318f4e783b5e5a18 10.0.0.18:6379@16379 master - 0 1603532399481 2 connected 5461-10922
6061cf2702a7c07bb64debbdc9bc7897a672d152 10.0.0.28:6379@16379 master - 0 1603532398460 3 connected 10923-16383
7a19f3c4082136d3d7c11f6a5c7665e461b2b565 10.0.0.58:6379@16379 slave 6061cf2702a7c07bb64debbdc9bc7897a672d152 0 1603532398000 6 connected
5a469424de6187f662ff825b40b3766fca893325 10.0.0.48:6379@16379 myself,slave 4457771149df7949b7d94cec318f4e783b5e5a18 0 1603532393000 5 connected
bb1c85f4a072be2d8645a40ecef76c358da29f3b 10.0.0.38:6379@16379 slave bfbbb2390cffddbdb6cad159658a4b8770702cd8 0 1603532400500 4 connected
bfbbb2390cffddbdb6cad159658a4b8770702cd8 10.0.0.8:6379@16379 master - 0 1603532400000 1 connected 0-5460

# 查看指定master节点的slave节点信息
redis-cli cluster slaves 
# 使用maste18的id查询其从节点48
[root@centos8 ~]#redis-cli -a 123456 cluster slaves 4457771149df7949b7d94cec318f4e783b5e5a18
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
1) "5a469424de6187f662ff825b40b3766fca893325 10.0.0.48:6379@16379 myself,slave 4457771149df7949b7d94cec318f4e783b5e5a18 0 1603532508000 5 connected"

5 验证集群状态

# 集群状态总览
[root@CentOS8 ~]#redis-cli -a 123456 --no-auth-warning CLUSTER INFO
cluster_state:ok
cluster_slots_assigned:16384
cluster_slots_ok:16384
cluster_slots_pfail:0
cluster_slots_fail:0
cluster_known_nodes:6    # 总结点数
cluster_size:3          # 集群数(一个主从架构就是一个集群)
cluster_current_epoch:6
cluster_my_epoch:1
cluster_stats_messages_ping_sent:2082
cluster_stats_messages_pong_sent:2042
cluster_stats_messages_sent:4124
cluster_stats_messages_ping_received:2037
cluster_stats_messages_pong_received:2082
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:4124

# 查看指定节点的集群状态
'使用选项 --cluster ,必须小写
[root@CentOS8 ~]#redis-cli -a 123456 --no-auth-warning --cluster info  10.0.0.58:6379
10.0.0.18:6379 (44577711...) -> 0 keys | 5462 slots | 1 slaves.
10.0.0.28:6379 (6061cf27...) -> 0 keys | 5461 slots | 1 slaves.
10.0.0.8:6379 (bfbbb239...) -> 0 keys | 5461 slots | 1 slaves.
[OK] 0 keys in 3 masters.
0.00 keys per slot on average.

6 查看集群node对应关系

# 总览
redis-cli -a 123456 --no-auth-warning CLUSTER NODES

# 指定任意节点进行全面检查
redis-cli -a 123456 --no-auth-warning --cluster check 10.0.0.48:6379

7 验证集群写入key

# 写入key的逻辑原理
1.客户端发送命令到任意节点
2.收到命令的节点进行定位:计算出槽位得到对应节点,判断是否指向自身
    2.1 指向自身:执行
    2.2 指向别处:回复moved。。。然后客户端重新对正确节点发送命令

7.1 redis cluster 写入key

# 指定节点8写入
[root@CentOS8 ~]#redis-cli -a 123456 --no-auth-warning -h 10.0.0.8 SET key1 values1
(error) MOVED 9189 10.0.0.18:6379
'算法根据key内容算出应放在 9189 槽位,此槽位不在当前节点,因此失败

# 指定正确节点写入
[root@CentOS8 ~]#redis-cli -a 123456 --no-auth-warning -h 10.0.0.18 SET key1 values1
OK
# 可查看值
[root@CentOS8 ~]#redis-cli -a 123456 --no-auth-warning -h 10.0.0.18 get key1 
"values1"

# 与之对应的从节点为48
从节点只能`keys *`不能`get key`
[root@centos8 ~]#redis-cli -a 123456 --no-auth-warning -h 10.0.0.48 get key1
(error) MOVED 9189 10.0.0.18:6379   '会提示正确位置'
[root@centos8 ~]#redis-cli -a 123456 --no-auth-warning -h 10.0.0.48 keys *
1) "key1"

7.2 redis cluster计算key所有slot

# 计算 xxx 对应的slot
redis-cli -h 10.0.0.8 -a 123456 --no-auth-warning cluster keyslot xxx

'注:cluster nodes可查看:3个master分别管辖 0-5461、5462-10922、10923-16383
[root@CentOS8 ~]#redis-cli -h 10.0.0.8 -a 123456 --no-auth-warning cluster keyslot hello
(integer) 866     '若set此key,应根据槽位选择正确的master节点,如866在0-5461:选择8'
[root@CentOS8 ~]#redis-cli -h 10.0.0.8 -a 123456 --no-auth-warning cluster keyslot caokunzi
(integer) 1481
[root@CentOS8 ~]#redis-cli -h 10.0.0.8 -a 123456 --no-auth-warning cluster keyslot zhubazi
(integer) 6488

# 使用选项 -c 以集群模式连接
# 集群模式使用(cluster keyslot xxx)查询指定key的槽位。。并且可直接set,自动保存在正确节点!!!
[root@CentOS8 ~]#redis-cli -c -h 10.0.0.8 -a 123456 --no-auth-warning
10.0.0.8:6379> cluster keyslot linux 
(integer) 12299
10.0.0.8:6379> set linux caokunzi
-> Redirected to slot [12299] located at 10.0.0.28:6379
OK
10.0.0.28:6379> get linux
"caokunzi"

# 由12299可知储存节点为 master-28
# 使用普通模式查看,必须要在28
[root@CentOS8 ~]#redis-cli -h 10.0.0.28 -a 123456 --no-auth-warning get linux
"caokunzi"
# 反例:
[root@CentOS8 ~]#redis-cli -h 10.0.0.18 -a 123456 --no-auth-warning get linux
(error) MOVED 12299 10.0.0.28:6379
[root@CentOS8 ~]#redis-cli -h 10.0.0.58 -a 123456 --no-auth-warning get linux
(error) MOVED 12299 10.0.0.28:6379

8 python脚本实现RedisCluster集群写入

# 环境准备(centos8)
dnf -y install python3
pip3 install redis-py-cluster

# 脚本: vim redis_cluster_test.py
#!/usr/bin/env python3
from rediscluster import RedisCluster
startup_nodes = [
    {"host":"10.0.0.8", "port":6379},
    {"host":"10.0.0.18", "port":6379},
    {"host":"10.0.0.28", "port":6379},
    {"host":"10.0.0.38", "port":6379},
    {"host":"10.0.0.48", "port":6379},
    {"host":"10.0.0.58", "port":6379}
]
redis_conn= RedisCluster(startup_nodes=startup_nodes,password='123456',decode_responses=True)
for i in range(0, 10000):
  redis_conn.set('key'+str(i),'value'+str(i))
  print('key'+str(i)+':',redis_conn.get('key'+str(i)))
  
# 权限
chmod +x redis_cluster_test.py

# 执行
./redis_cluster_test.py     # 注意: bash 命令用来执行shell脚本!这是python脚本
============================================================================
# 检查数据
[root@CentOS8 ~]#redis-cli -a 123456 -h 10.0.0.8 --no-auth-warning
10.0.0.8:6379> DBSIZE
(integer) 3331                # 什么指标????
10.0.0.8:6379> get key1
(error) MOVED 9189 10.0.0.18:6379
10.0.0.8:6379> get key145
"value145"
10.0.0.8:6379> get key777
"value777"
10.0.0.8:6379> get key2828
(error) MOVED 10495 10.0.0.18:6379

[root@centos8 ~]#redis-cli -a 123456 -h 10.0.0.18 --no-auth-warning
10.0.0.18:6379> DBSIZE
(integer) 3340
10.0.0.18:6379> get key1
"value1"
10.0.0.18:6379> get key2828
"value2828"
10.0.0.18:6379> get key9999
(error) MOVED 3339 10.0.0.8:6379
10.0.0.18:6379> 
==========================================================================
# 主从一致
[root@centos8 ~]#redis-cli -a 123456 -h 10.0.0.8 --no-auth-warning dbsize
(integer) 3331
[root@centos8 ~]#redis-cli -a 123456 -h 10.0.0.18 --no-auth-warning dbsize
(integer) 3340
[root@centos8 ~]#redis-cli -a 123456 -h 10.0.0.28 --no-auth-warning dbsize
(integer) 3330
[root@centos8 ~]#redis-cli -a 123456 -h 10.0.0.38 --no-auth-warning dbsize
(integer) 3331
[root@centos8 ~]#redis-cli -a 123456 -h 10.0.0.48 --no-auth-warning dbsize
(integer) 3340
[root@centos8 ~]#redis-cli -a 123456 -h 10.0.0.58 --no-auth-warning dbsize
(integer) 3330

9 模拟master故障,对应的slave节点自动提升为新master

# 模拟node2节点(10.0.0.18)出故障,需要数秒故障转移时间
===================================================
# 首先在节点2开启日志
tail -f /var/log/redis/redis.log 

# 登录node2节点关机
[root@centos8 ~]#redis-cli -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:6379> 
127.0.0.1:6379> 
127.0.0.1:6379> shutdown
not connected> exit
[root@centos8 ~]#ss -ntl
State        Recv-Q        Send-Q                Local Address:Port               Peer Address:Port   
LISTEN       0             128                         0.0.0.0:22                      0.0.0.0:*    
LISTEN       0             100                       127.0.0.1:25                      0.0.0.0:*  
LISTEN       0             128                         0.0.0.0:111                     0.0.0.0:* 
LISTEN       0             128                            [::]:22                         [::]:* 
LISTEN       0             100                           [::1]:25                         [::]:* 
LISTEN       0             128                            [::]:111                        [::]:*  

# 查看集群的主从关系
[root@CentOS8 ~]#redis-cli -a 123456 --cluster info 10.0.0.8:6379
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
Could not connect to Redis at 10.0.0.18:6379: Connection refused
10.0.0.8:6379 (bfbbb239...) -> 3331 keys | 5461 slots | 1 slaves.
10.0.0.48:6379 (5a469424...) -> 3340 keys | 5462 slots | 0 slaves.  # 48成为新主
10.0.0.28:6379 (6061cf27...) -> 3330 keys | 5461 slots | 1 slaves.
[OK] 10001 keys in 3 masters.
0.61 keys per slot on average.

# 主从详细信息
[root@CentOS8 ~]#redis-cli -a 123456 --cluster check 10.0.0.8:6379
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
Could not connect to Redis at 10.0.0.18:6379: Connection refused
10.0.0.8:6379 (bfbbb239...) -> 3331 keys | 5461 slots | 1 slaves.
10.0.0.48:6379 (5a469424...) -> 3340 keys | 5462 slots | 0 slaves.
10.0.0.28:6379 (6061cf27...) -> 3330 keys | 5461 slots | 1 slaves.
[OK] 10001 keys in 3 masters.
0.61 keys per slot on average.
>>> Performing Cluster Check (using node 10.0.0.8:6379)
M: bfbbb2390cffddbdb6cad159658a4b8770702cd8 10.0.0.8:6379
   slots:[0-5460] (5461 slots) master
   1 additional replica(s)
S: bb1c85f4a072be2d8645a40ecef76c358da29f3b 10.0.0.38:6379
   slots: (0 slots) slave
   replicates bfbbb2390cffddbdb6cad159658a4b8770702cd8
M: 5a469424de6187f662ff825b40b3766fca893325 10.0.0.48:6379
   slots:[5461-10922] (5462 slots) master
M: 6061cf2702a7c07bb64debbdc9bc7897a672d152 10.0.0.28:6379
   slots:[10923-16383] (5461 slots) master
   1 additional replica(s)
S: 7a19f3c4082136d3d7c11f6a5c7665e461b2b565 10.0.0.58:6379
   slots: (0 slots) slave
   replicates 6061cf2702a7c07bb64debbdc9bc7897a672d152
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.

# 指定查看 48 的主从关系
[root@CentOS8 ~]#redis-cli -a 123456 -h 10.0.0.48 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:0
master_replid:230a53c5beda83e2de9550acdc67cddee48c3842
master_replid2:d12f0146815127bb80a434cd4a48269cc166dbf1
master_repl_offset:144009
second_repl_offset:144010
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:144009
==================================
# 恢复故障节点node2
systemctl start redis

# 查看日志
18247:S 24 Oct 2020 18:47:18.743 # Cluster state changed: ok
18247:S 24 Oct 2020 18:47:19.761 * Connecting to MASTER 10.0.0.48:6379
18247:S 24 Oct 2020 18:47:19.762 * MASTER <-> REPLICA sync started
18247:S 24 Oct 2020 18:47:19.762 * Non blocking connect for SYNC fired the event.
18247:S 24 Oct 2020 18:47:19.762 * Master replied to PING, replication can continue...
18247:S 24 Oct 2020 18:47:19.763 * Trying a partial resynchronization (request 06e7c1999b779c409e9fce434f5d4a212041a070:1).
18247:S 24 Oct 2020 18:47:19.763 * Full resync from master: 230a53c5beda83e2de9550acdc67cddee48c3842:144009
18247:S 24 Oct 2020 18:47:19.763 * Discarding previously cached master state.
18247:S 24 Oct 2020 18:47:19.857 * MASTER <-> REPLICA sync: receiving 62898 bytes from master
18247:S 24 Oct 2020 18:47:19.857 * MASTER <-> REPLICA sync: Flushing old data
18247:S 24 Oct 2020 18:47:19.858 * MASTER <-> REPLICA sync: Loading DB in memory
18247:S 24 Oct 2020 18:47:19.860 * MASTER <-> REPLICA sync: Finished with success

# 指定查看 48 的主从关系
[root@CentOS8 ~]#redis-cli -a 123456 -h 10.0.0.48 info replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:1
slave0:ip=10.0.0.18,port=6379,state=online,offset=144093,lag=1  # 18已经成为48的从
master_replid:230a53c5beda83e2de9550acdc67cddee48c3842
master_replid2:d12f0146815127bb80a434cd4a48269cc166dbf1
master_repl_offset:144093
second_repl_offset:144010
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:144093

你可能感兴趣的:(2020-10-25 Redis)