博客作业第六周-企业级NoSQL数据库redis-持久化、集群与高可用

一、RDB和AOF的优缺点

RDB模式优缺点

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

比如: 可以在最近的24小时内,每小时备份一次RDB文件,并且在每个月的每一天,也备份一个
RDB文件。这样的话,即使遇上问题,也可以随时将数据集还原到不同的版本。

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

RDB在大量数据,比如几个G的数据,恢复的速度比AOF的快
缺点:
不能实时保存数据,可能会丢失自上一次执行RDB备份到当前的内存数据
如果你需要尽量避免在服务器故障时丢失数据,那么RDB不适合你。虽然Redis允许你设置不同的
保存点(save point)来控制保存RDB文件的频率,但是,因为RDB文件需要保存整个数据集的状
态,所以它并不是一个轻松的操作。因此你可能会至少5分钟才保存一次RDB文件。在这种情况
下,一旦发生故障停机,你就可能会丢失好几分钟的数据。

当数据量非常大的时候,从父进程fork子进程进行保存至RDB文件时需要一点时间,可能是毫秒或
者秒,取决于磁盘IO性能。
在数据集比较庞大时,fork()可能会非常耗时,造成服务器在一定时间内停止处理客户端﹔如果数据集非常巨大,并且CPU时间非常紧张的话,那么这种停止时间甚至可能会长达整整一秒或更久。虽然 AOF重写也需要进行fork(),但无论AOF重写的执行间隔有多长,数据的持久性都不会有任何损失。

AOF模式

优点

数据安全性相对较高,根据所使用的fsync策略(fsync是同步内存中redis所有已经修改的文件到存
储设备),默认是appendfsync everysec,即每秒执行一次 fsync,在这种配置下,Redis 仍然可以
保持良好的性能,并且就算发生故障停机,也最多只会丢失一秒钟的数据( fsync会在后台线程执
行,所以主线程可以继续努力地处理命令请求)
由于该机制对日志文件的写入操作采用的是append模式,因此在写入过程中不需要seek, 即使出
现宕机现象,也不会破坏日志文件中已经存在的内容。然而如果本次操作只是写入了一半数据就出
现了系统崩溃问题,不用担心,在Redis下一次启动之前,可以通过 redis-check-aof 工具来解决
数据一致性的问题
Redis可以在 AOF文件体积变得过大时,自动地在后台对AOF进行重写,重写后的新AOF文件包含了
恢复当前数据集所需的最小命令集合。整个重写操作是绝对安全的,因为Redis在创建新 AOF文件
的过程中,append模式不断的将修改数据追加到现有的 AOF文件里面,即使重写过程中发生停
机,现有的 AOF文件也不会丢失。而一旦新AOF文件创建完毕,Redis就会从旧AOF文件切换到新
AOF文件,并开始对新AOF文件进行追加操作。
AOF包含一个格式清晰、易于理解的日志文件用于记录所有的修改操作。事实上,也可以通过该文
件完成数据的重建
AOF文件有序地保存了对数据库执行的所有写入操作,这些写入操作以Redis协议的格式保存,因
此 AOF文件的内容非常容易被人读懂,对文件进行分析(parse)也很轻松。导出(export)AOF文件
也非常简单:举个例子,如果你不小心执行了FLUSHALL.命令,但只要AOF文件未被重写,那么只
要停止服务器,移除 AOF文件末尾的FLUSHAL命令,并重启Redis ,就可以将数据集恢复到
FLUSHALL执行之前的状态。
缺点:
即使有些操作是重复的也会全部记录,AOF 的文件大小要大于 RDB 格式的文件
AOF 在恢复大数据集时的速度比 RDB 的恢复速度要慢
根据fsync策略不同,AOF速度可能会慢于RDB
bug 出现的可能性更多

二、master和slave同步过程

2.1、redis主从复制

主从复制分为全量同步和增量同步

2.1.1、全量复制原理

在这里插入图片描述
从节点主动向主节点发送psync指令请求同步,主节点将runid和offset发送给请求同步的从服务器,从服务器将两个信息保存下来(runid是每次redis启动生成的临时标号,查看方法如下)主节点开启子进程执行bgsave命令,生成rdb快照,生成rdb快照后将文件发送给从节点,如果此时主节点还有新数据产生将会放到buffer缓冲区中,等待rdb文件发送完成再将buffer缓冲区的数据发送给从节点 ,从节点收到后自动清除自己的旧数据,slave将收到后的rdb文 件载入自己的内存,再加载所有收到缓冲区的内容 从而这样一次完整的数据同步。

[root@centos8 ~]#redis-cli 
127.0.0.1:6379> info
# Server
redis_version:5.0.3
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:28849dbea6f07cc8
redis_mode:standalone
os:Linux 4.18.0-147.el8.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:8.3.1
process_id:747
run_id:110407290e3616e3b7d772149b51009a6fe31f10      #runid
tcp_port:6379
uptime_in_seconds:33226
uptime_in_days:0
hz:10
master_repl_offset:0                                #
second_repl_offset:-1                               #

2.1.2、增量复制原理

在这里插入图片描述

假如主从直接发生故障断开连接,主节点发生新数据变化会将数据写入到buffer缓冲区中,从节点重新连接主节点,从节点将自己的runid和offset发送给主节点,主节点收到从节点的pysnc后回复确认同步,再将发生变化的数据发送给从节点。

一定要保证复制缓冲区大小,否则一旦空间不足将会覆盖原有数据,生产中一定要保证主从节点配置文件一致

2.1.3、实现主从复制(命令行方式重启配置丢失)

实验环境: 10.0.0.68   centos8   master
		 10.0.0.58   centos8   slave
2.1.3.1、主节点通过更改配置文件或者临时修改设置密码,执行测试脚本生成测试数据
[root@centos8 ~]#cat redis_test.py 
#!/bin/env python3
import redis
pool = redis.ConnectionPool(host="127.0.0.1",port=6379,password="123456")
r = redis.Redis(connection_pool=pool)
for i in range(10000):
    r.set("key%d" % i,"value%d" % i)
    data=r.get("key%d" % i)
    print(data)
2.1.3.2、在从节点执行命令
#REPLICAOF+主节点IP地址+端口号
127.0.0.1:6379> REPLICAOF 10.0.0.68 6379
OK
#123456为主节点redis密码
127.0.0.1:6379> CONFIG SET masterauth 123456
OK
2.1.3.3、在从节点查看数据是否同步成功及同步状态
127.0.0.1:6379> INFO replication
# Replication
role:slave                     #当前角色为slave
master_host:10.0.0.68
master_port:6379
master_link_status:up
master_last_io_seconds_ago:3
master_sync_in_progress:0
slave_repl_offset:56
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:cced0f4df71683f7e896fe7bfe2574ab564b81b0
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:56
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:56
#查看数据量
127.0.0.1:6379> DBSIZE
(integer) 10005
2.1.3.4、查看主节点状态
127.0.0.1:6379> info replication
# Replication
role:master         #角色为master
connected_slaves:1
slave0:ip=10.0.0.58,port=6379,state=online,offset=756,lag=1
master_replid:cced0f4df71683f7e896fe7bfe2574ab564b81b0
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:756
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:756
127.0.0.1:6379> DBSIZE
(integer) 10005
2.1.3.5、主从复制测试
#在主机点创建测试值
127.0.0.1:6379> set car BYD
OK
#在从节点查看是否能够同步成功
127.0.0.1:6379> GET car
"BYD"

从节点在搭建好主从复制之后,将无法再进行赋值等写入操作,为只读模式

2.1.4、实现主从复制(更改配置文件方法永久保存)

[root@Centos8 ~]#vim /etc/redis.conf
# 1) Redis replication is asynchronous, but you can configure a master to
#    stop accepting writes if it appears to be not connected with at least
#    a given number of replicas.
# 2) Redis replicas are able to perform a partial resynchronization with the
#    master if the replication link is lost for a relatively small amount of
#    time. You may want to configure the replication backlog size (see the next
#    sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
#    network partition replicas automatically try to reconnect to masters
#    and resynchronize with them.
#
 replicaof  10.0.0.68 6379      

# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the replica to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the replica request.
#
 masterauth 123456
 #更改完成后重启服务

2.1.5、实现redis的级联复制

在这里插入图片描述
实验环境:

10.0.0.68  centos8  master
10.0.0.58  centos8  slave1
10.0.0.48  centos8  slave2

10.0.0.68和10.0.0.58实验环境使用上一个主从复制环境,新增10.0.0.48节点

#新节点安装redis
[root@Centos8 ~]#yum -y install redis
#修改配置文件,并重启服务
 replicaof 10.0.0.58 6379        #replicaof+slave1 IP地址+端口号
#这里要注意10.0.0.58(slave1)是否有密码及6379端口绑定状态
#测试是否同步成功
[root@Centos8 ~]#redis-cli get car
"BYD"

2.1.6、停止slave同步提升为新的master

127.0.0.1:6379> REPLICAOF NO ONE  #旧版使用SLAVEOF no one
OK
(5.04s)
127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:0
master_replid:94901d6b8ff812ec4a4b3ac6bb33faa11e55c274
master_replid2:0083e5a9c96aa4f2196934e10b910937d82b4e19
master_repl_offset:3514
second_repl_offset:3515
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:3431
repl_backlog_histlen:84
127.0.0.1:6379>

测试能否写入数据(只有主节点可以写数据,从节点只能都数据)

127.0.0.1:6379> set keytest1 vtest1
OK

og_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:3431
repl_backlog_histlen:84
127.0.0.1:6379>


测试能否写入数据(只有主节点可以写数据,从节点只能都数据)

```bash
127.0.0.1:6379> set keytest1 vtest1
OK

三、哨兵的使用和实现机制

Sentinel 进程是用于监控redis集群中Master主服务器工作的状态,在Master主服务器发生故障的时
候,可以实现Master和Slave服务器的切换,保证系统的高可用,此功能在redis2.6+的版本已引用,
Redis的哨兵模式到了2.8版本之后就稳定了下来。一般在生产环境也建议使用Redis的2.8版本的以后版

哨兵(Sentinel) 是一个分布式系统,可以在一个架构中运行多个哨兵(sentinel) 进程,这些进程使用流言
协议(gossip protocols)来接收关于Master主服务器是否下线的信息,并使用投票协议(Agreement
Protocols)来决定是否执行自动故障迁移,以及选择哪个Slave作为新的Master
每个哨兵(Sentinel)进程会向其它哨兵(Sentinel)、Master、Slave定时发送消息,以确认对方是否”活”
着,如果发现对方在指定配置时间(此项可配置)内未得到回应,则暂时认为对方已离线,也就是所谓的”
主观认为宕机” (主观:是每个成员都具有的独自的而且可能相同也可能不同的意识),英文名称:
Subjective Down,简称SDOWN
有主观宕机,对应的有客观宕机。当“哨兵群”中的多数Sentinel进程在对Master主服务器做出SDOWN
的判断,并且通过 SENTINEL is-master-down-by-addr 命令互相交流之后,得出的Master Server下线
判断,这种方式就是“客观宕机”(客观:是不依赖于某种意识而已经实际存在的一切事物),英文名称是:
Objectively Down, 简称 ODOWN
通过一定的vote算法,从剩下的slave从服务器节点中,选一台提升为Master服务器节点,然后自动修
改相关配置,并开启故障转移(failover)
Sentinel 机制可以解决master和slave角色的自动切换问题,但单个 Master 的性能瓶颈问题无法解决,
类似于MySQL中的MHA功能
Redis Sentinel中的Sentinel节点个数应该为大于等于3且最好为奇数
客户端初始化时连接的是Sentinel节点集合,不再是具体的Redis节点,但Sentinel只是配置中心不是代
理。
Redis Sentinel 节点与普通redis 没有区别,要实现读写分离依赖于客户端程序
redis 3.0 之前版本中,生产环境一般使用哨兵模式,但3.0后推出redis cluster功能后,可以支持更大规模的
生产环境

哨兵以后台方式运行,一般为奇数节点,避免脑裂产生
在这里插入图片描述

实验环境:

10.0.0.68   centos8  master
10.0.0.58   centos8  slave1
10.0.0.48   centos8  slave2

3.1、准备主从环境

#所有节点安装redis,修改配置文件
[root@Centos8 ~]#vim /etc/redis.conf 
bind 0.0.0.0             #允许所有主机访问本机
masterauth "123456"      #主节点redis密码
requirepass "123456"     #本机redis密码

从节点配置文件添加主从复制配置信息

#直接追加
[root@centos8 ~]#echo "replicaof 10.0.0.68 6379" >> /etc/redis.conf
#或者配置文件中修改
replicaof 10.0.0.68 6379

启动所有节点的redis服务

systemctl enable --now redis

查看主节点和从节点状态

#主节点信息
127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:2
slave0:ip=10.0.0.58,port=6379,state=online,offset=462,lag=1
slave1:ip=10.0.0.48,port=6379,state=online,offset=462,lag=0
master_replid:48dd9b87c8a95054e40a93c7badbaa6d4ed82f43
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:462
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:462
#slave1
127.0.0.1:6379> info replication
# Replication
role:slave
master_host:10.0.0.68
master_port:6379
master_link_status:up
master_last_io_seconds_ago:9
master_sync_in_progress:0
slave_repl_offset:490
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:48dd9b87c8a95054e40a93c7badbaa6d4ed82f43
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:490
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:490
#slave2
127.0.0.1:6379> info replication
# Replication
role:slave
master_host:10.0.0.68
master_port:6379
master_link_status:up
master_last_io_seconds_ago:1
master_sync_in_progress:0
slave_repl_offset:532
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:48dd9b87c8a95054e40a93c7badbaa6d4ed82f43
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:532
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:532

3.2、配置哨兵

三个节点都进行配置

[root@centos8 ~]#vim /etc/redis-sentinel.conf 
sentinel monitor mymaster 10.0.0.68 6379 2     #指定当前mymaster集群中master服务器的地址和端口
sentinel auth-pass mymaster 123456             #mymaster集群中master的密码此项必须跟在上面行的下面,2为法定人数限制(quorum),即有几个sentinel认为master down了就进行故障转移,一般此值是所有sentinel节点(一般总数是>=3的 奇数,如:3,5,7等)的一半以上的整数值,比如,总数是3,即3/2=1.5,取整为2,是master的ODOWN客观下线的依据
sentinel down-after-milliseconds mymaster 3000   #判断mymaster集群中所有节点的主观下线的时间默认30秒这里改为3秒

配置完成启动sentinel服务

[root@centos8 ~]#systemctl enable redis-sentinel.service --now

查看sentinel状态

[root@centos8 ~]#redis-cli -a 123456 -p 26379
# 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

3.3、停止Redis Master测试故障转移

#停止主节点redis服务
[root@centos8 ~]#systemctl stop redis.service 
#以下为sentinel日志内容
2001:X 24 Oct 2020 20:16:27.227 # +sdown master mymaster 10.0.0.68 6379
2001:X 24 Oct 2020 20:16:27.263 # +new-epoch 1
2001:X 24 Oct 2020 20:16:27.264 # +vote-for-leader 36a52d40b77ebb844647351641b3ecb83c0d6046 1
2001:X 24 Oct 2020 20:16:27.318 # +odown master mymaster 10.0.0.68 6379 #quorum 3/2
2001:X 24 Oct 2020 20:16:27.318 # Next failover delay: I will not start a failover before Sat Oct 24 20:22:28 2020
2001:X 24 Oct 2020 20:16:27.920 # +config-update-from sentinel 36a52d40b77ebb844647351641b3ecb83c0d6046 10.0.0.48 26379 @ mymaster 10.0.0.68 6379
2001:X 24 Oct 2020 20:16:27.920 # +switch-master mymaster 10.0.0.68 6379 10.0.0.48 6379           #日志提示新主节点为10.0.0.48服务器
2001:X 24 Oct 2020 20:16:27.921 * +slave slave 10.0.0.58:6379 10.0.0.58 6379 @ mymaster 10.0.0.48 6379
2001:X 24 Oct 2020 20:16:27.921 * +slave slave 10.0.0.68:6379 10.0.0.68 6379 @ mymaster 10.0.0.48 6379
2001:X 24 Oct 2020 20:16:30.932 # +sdown slave 10.0.0.68:6379 10.0.0.68 6379 @ mymaster 10.0.0.48 6379
#在10.0.0.48机器查看
[root@Centos8 ~]#redis-cli -a 123456 -p 26379
# 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.48:6379,slaves=2,sentinels=3

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

当故障节点10.0.0.68恢复后会自动称为从节点配置文件也会自动更改

[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> info replication
# Replication
role:slave
master_host:10.0.0.48
master_port:6379
master_link_status:up
master_last_io_seconds_ago:1
master_sync_in_progress:0
slave_repl_offset:316481
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:cd0e62e05011cc15273c388d50a1655c65e03e70
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:316481
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:315661
repl_backlog_histlen:821

手动让主节点下线

[root@centos8 ~]#redis-cli  -p 26379
127.0.0.1:26379> sentinel failover mymaster
OK

1048576
repl_backlog_first_byte_offset:315661
repl_backlog_histlen:821


手动让主节点下线

```bash
[root@centos8 ~]#redis-cli  -p 26379
127.0.0.1:26379> sentinel failover mymaster
OK

四、redis cluster集群创建和使用

4.1、基于redis5的redis集群部署

4.1.1、环境准备

实验环境:
10.0.0.68   centos8
10.0.0.58   centos8
10.0.0.48   centos8
10.0.0.38   centos8
10.0.0.28   centos8
10.0.0.18   centos8

每台主机都安装redis

[root@centos8 ~]#yum -y install redis

4.1.2、配置redis

每个节点修改redis配置,必须开启cluster功能的参数

#手动修改配置文件
[root@redis-node1 ~]vim /etc/redis.conf
bind 0.0.0.0
masterauth 123456  #建议配置,否则后期的master和slave主从复制无法成功,还需再配置
requirepass 123456
cluster-enabled yes #取消此行注释,必须开启集群,开启后redis 进程会有cluster显示
cluster-config-file nodes-6379.conf #取消此行注释,此为集群状态文件,记录主从关系及
slot范围信息,由redis cluster 集群自动创建和维护
cluster-require-full-coverage no  #默认值为yes,设为no可以防止一个节点不可用导致整
个cluster不可能
#或者执行下面命令,批量修改
[root@Centos8 ~]#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 
#启动服务
[root@centos8 ~]#systemctl enable redis --now
Created symlink /etc/systemd/system/multi-user.target.wants/redis.service → /usr/lib/systemd/system/redis.service.
[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               128                             0.0.0.0:16379                          0.0.0.0:*             
LISTEN         0               128                             0.0.0.0:6379                           0.0.0.0:*             
LISTEN         0               128                                [::]:22                                [::]:*   

4.1.3、创建集群

#默认前三个为master,后三个依次为前三个master的slave,redis-cli --cluster-replicas 1 表示每个master对应一个slave节点
[root@centos8 ~]#redis-cli -a 123456 --cluster create 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 10.0.0.68: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.48:6379 to 10.0.0.18:6379
Adding replica 10.0.0.58:6379 to 10.0.0.28:6379
Adding replica 10.0.0.68:6379 to 10.0.0.38:6379
M: 21df7ebc3557a48630c6417f3e1e24f8e8290b63 10.0.0.18:6379
   slots:[0-5460] (5461 slots) master
M: ca89953e0f9abb3efe6f13a4e7b0beeec8297934 10.0.0.28:6379
   slots:[5461-10922] (5462 slots) master
M: be4e98db5c8fc637d7ad3424f5dd48f557256252 10.0.0.38:6379
   slots:[10923-16383] (5461 slots) master
S: a8579d5a56e4e0f9e953d74dc9aa25b18a2c3e66 10.0.0.48:6379
   replicates 21df7ebc3557a48630c6417f3e1e24f8e8290b63
S: f2be622a81da5f64c22eed8ecff84a606e1887b5 10.0.0.58:6379
   replicates ca89953e0f9abb3efe6f13a4e7b0beeec8297934
S: b9556a8b7f46741f639584ff447f21a31334ca4b 10.0.0.68:6379
   replicates be4e98db5c8fc637d7ad3424f5dd48f557256252
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.18:6379)
M: 21df7ebc3557a48630c6417f3e1e24f8e8290b63 10.0.0.18:6379
   slots:[0-5460] (5461 slots) master
   1 additional replica(s)
M: ca89953e0f9abb3efe6f13a4e7b0beeec8297934 10.0.0.28:6379
   slots:[5461-10922] (5462 slots) master
   1 additional replica(s)
M: be4e98db5c8fc637d7ad3424f5dd48f557256252 10.0.0.38:6379
   slots:[10923-16383] (5461 slots) master
   1 additional replica(s)
S: a8579d5a56e4e0f9e953d74dc9aa25b18a2c3e66 10.0.0.48:6379
   slots: (0 slots) slave
   replicates 21df7ebc3557a48630c6417f3e1e24f8e8290b63
S: b9556a8b7f46741f639584ff447f21a31334ca4b 10.0.0.68:6379
   slots: (0 slots) slave
   replicates be4e98db5c8fc637d7ad3424f5dd48f557256252
S: f2be622a81da5f64c22eed8ecff84a606e1887b5 10.0.0.58:6379
   slots: (0 slots) slave
   replicates ca89953e0f9abb3efe6f13a4e7b0beeec8297934
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.

4.1.4、查看主从状态

127.0.0.1:6379> info replication
# Replication
role:slave
master_host:10.0.0.38
master_port:6379
master_link_status:up
master_last_io_seconds_ago:1
master_sync_in_progress:0
slave_repl_offset:742
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:c39521ced8199b770d6ee9d4c58abe55eaa8ed62
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:742
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:742

4.1.5、python脚本实现redis cluster 集群写入

[root@centos8 ~]#yum -y install python3
[root@centos8 ~]#pip3 install redis-py-cluster
#数据写入脚本
[root@centos8 ~]#cat redis_cluster_test.py 
#!/usr/bin/env python3
from rediscluster  import RedisCluster
startup_nodes = [
    {"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},
    {"host":"10.0.0.68", "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)))
[root@centos8 ~]#chmod +x redis_cluster_test.py
[root@centos8 ~]#./redis_cluster_test.py 
[root@centos8 ~]#redis-cli -a 123456 -h 10.0.0.38
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
10.0.0.38:6379> DBSIZE
(integer) 3329

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

将master10.0.0.28服务停掉,再查看集群信息,10.0.0.28对应的从节点10.0.0.58自动提升为新主

#查看集群的主从主从关系和槽位信息
[root@centos8 ~]#redis-cli -a 123456 cluster slots
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
1) 1) (integer) 0
   2) (integer) 5460
   3) 1) "10.0.0.18"
      2) (integer) 6379
      3) "21df7ebc3557a48630c6417f3e1e24f8e8290b63"
   4) 1) "10.0.0.48"
      2) (integer) 6379
      3) "a8579d5a56e4e0f9e953d74dc9aa25b18a2c3e66"
2) 1) (integer) 5461
   2) (integer) 10922
   3) 1) "10.0.0.58"
      2) (integer) 6379
      3) "f2be622a81da5f64c22eed8ecff84a606e1887b5"
3) 1) (integer) 10923
   2) (integer) 16383
   3) 1) "10.0.0.38"
      2) (integer) 6379
      3) "be4e98db5c8fc637d7ad3424f5dd48f557256252"
   4) 1) "10.0.0.68"
      2) (integer) 6379
      3) "b9556a8b7f46741f639584ff447f21a31334ca4b"
 [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.
21df7ebc3557a48630c6417f3e1e24f8e8290b63 10.0.0.18:6379@16379 master - 0 1603615467230 1 connected 0-5460
f2be622a81da5f64c22eed8ecff84a606e1887b5 10.0.0.58:6379@16379 master - 0 1603615466000 7 connected 5461-10922
a8579d5a56e4e0f9e953d74dc9aa25b18a2c3e66 10.0.0.48:6379@16379 slave 21df7ebc3557a48630c6417f3e1e24f8e8290b63 0 1603615463000 4 connected
ca89953e0f9abb3efe6f13a4e7b0beeec8297934 10.0.0.28:6379@16379 master,fail - 1603615132603 1603615131000 2 disconnected
be4e98db5c8fc637d7ad3424f5dd48f557256252 10.0.0.38:6379@16379 master - 0 1603615467000 3 connected 10923-16383
b9556a8b7f46741f639584ff447f21a31334ca4b 10.0.0.68:6379@16379 myself,slave be4e98db5c8fc637d7ad3424f5dd48f557256252 0 1603615463000 6 connected
#将停掉服务的10.0.0.28恢复,自动变为10.0.0.58的从节点
[root@Centos8-test ~]#systemctl start redis
[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.
21df7ebc3557a48630c6417f3e1e24f8e8290b63 10.0.0.18:6379@16379 master - 0 1603616154975 1 connected 0-5460
f2be622a81da5f64c22eed8ecff84a606e1887b5 10.0.0.58:6379@16379 master - 0 1603616156000 7 connected 5461-10922
a8579d5a56e4e0f9e953d74dc9aa25b18a2c3e66 10.0.0.48:6379@16379 slave 21df7ebc3557a48630c6417f3e1e24f8e8290b63 0 1603616156988 4 connected
ca89953e0f9abb3efe6f13a4e7b0beeec8297934 10.0.0.28:6379@16379 slave f2be622a81da5f64c22eed8ecff84a606e1887b5 0 1603616153000 7 connected
be4e98db5c8fc637d7ad3424f5dd48f557256252 10.0.0.38:6379@16379 master - 0 1603616155000 3 connected 10923-16383
b9556a8b7f46741f639584ff447f21a31334ca4b 10.0.0.68:6379@16379 myself,slave be4e98db5c8fc637d7ad3424f5dd48f557256252 0 1603616155000 6 connected

4.2、基于rendis 4.0部署redis cluster

使用六台centos7服务器

[root@localhost ~]#vim install_redis_for_centos.sh  #自动编译安装redis4.0.14脚本

#!/bin/bash
. /etc/init.d/functions 
VERSION=redis-4.0.14
PASSWORD=123456
INSTALL_DIR=/apps/redis

install() {
yum  -y install gcc jemalloc-devel || { action "安装软件包失败,请检查网络配置" false ; exit; }

wget http://download.redis.io/releases/${VERSION}.tar.gz || { action "Redis 源码下载失败" false ; exit; }



tar xf ${VERSION}.tar.gz
cd ${VERSION}


ln -s ${INSTALL_DIR}/bin/redis-*  /usr/bin/
mkdir -p ${INSTALL_DIR}/{etc,log,data,run}
cp redis.conf  ${INSTALL_DIR}/etc/



if id redis &> /dev/null ;then 
    action "Redis 用户已存在" false  
else
    useradd -r -s /sbin/nologin redis
    action "Redis 用户创建成功"
fi

chown -R redis.redis ${INSTALL_DIR}

vm.overcommit_memory = 1
EOF
sysctl -p 

echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local
/etc/rc.d/rc.local

cat > /usr/lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=${INSTALL_DIR}/bin/redis-server ${INSTALL_DIR}/etc/redis.conf --supervised systemd
ExecStop=/bin/kill -s QUIT \$MAINPID
Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target

EOF
systemctl daemon-reload 
systemctl enable --now  redis &> /dev/null && action "Redis 服务启动成功,Redis信息如下:" || { action "Redis 启动失败" false ;exit; } 

redis-cli -a $PASSWORD INFO Server 2> /dev/null

}

install

[17:24:51 root@localhost ~]#bash install_redis_for_centos.sh #在所有节点执行脚本来安装redis
[17:53:59 root@localhost ~]#sed -i -e '/^# masterauth/a masterauth 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' /apps/redis/etc/redis.conf #修改所有reids的配置文件
[17:41:51 root@localhost ~]#systemctl restart redis #重启redis
[17:56:24 root@localhost ~]#cp redis-4.0.14/src/redis-trib.rb /usr/bin/ #拷贝redis-trib.rb工具到/usr/bin下,方便使用
[18:24:54 root@localhost ~]#yum -y install ruby #安装ruby环境,但是由于cneots7yum安装ruby版本太低,需要执行其他操作
[18:52:33 root@localhost ~]#yum -y install gcc openssl-devel zlib-devel #安装编译ruby依赖包
[18:53:00 root@localhost ~]#wget https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.5.tar.gz #下载ruby2.5.5的源码包
--2020-10-25 18:53:24--  https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.5.tar.gz
Resolving cache.ruby-lang.org (cache.ruby-lang.org)... 151.101.77.178, 2a04:4e42:12::434
Connecting to cache.ruby-lang.org (cache.ruby-lang.org)|151.101.77.178|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 15996436 (15M) [application/x-tar]
Saving to: ‘ruby-2.5.5.tar.gz’

100%[=================================================================>] 15,996,436  82.9KB/s   in 2m 57s 

2020-10-25 18:56:27 (88.2 KB/s) - ‘ruby-2.5.5.tar.gz’ saved [15996436/15996436]


[18:56:27 root@localhost ~]#tar xf ruby-2.5.5.tar.gz  #解压源码包
[18:58:51 root@localhost ruby-2.5.5]#cd ruby-2.5.5 
[18:58:51 root@localhost ruby-2.5.5]#./configure #执行configure脚本生成makefile文件
[18:59:33 root@localhost ruby-2.5.5]#make && make install #编译安装ruby
[19:06:18 root@localhost ruby-2.5.5]#ruby -v
ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux] #查看ruby版本,然后重新登录终端
[19:17:37 root@localhost ~]#gem install -l redis-4.1.3.gem #安装redis模块,此为安装离线包,需提前将文件下载好,下载链接:https://rubygems.org/downloads/redis-4.1.3.gem ,注意下载此包需要科学上网
Successfully installed redis-4.1.3
Parsing documentation for redis-4.1.3
Installing ri documentation for redis-4.1.3
Done installing documentation for redis after 0 seconds
1 gem installed
[19:20:38 root@localhost ~]#vi /usr/local/lib/ruby/gems/2.5.0/gems/redis-4.1.3/lib/redis/client.rb 

# frozen_string_literal: true

require_relative "errors"
require "socket"
require "cgi"

class Redis
  class Client

    DEFAULTS = {
      :url => lambda { ENV["REDIS_URL"] },
      :scheme => "redis",
      :host => "127.0.0.1",
      :port => 6379,
      :path => nil,
      :timeout => 5.0,
      :password => 123456,   #修改脚本中连接redis的密码                                                                               
      :db => 0,
      :driver => nil,
      :id => nil,
      :tcp_keepalive => 0,
      :reconnect_attempts => 1,
      :reconnect_delay => 0,
      :reconnect_delay_max => 0.5,
      :inherit_socket => false
    }

    attr_reader :options

[19:21:49 root@localhost ~]#redis-trib.rb create --replicas 1 10.0.0.7:6379 10.0.0.17:6379 10.0.0.27:6379 10.0.0.37:6379 10.0.0.47:6379 10.0.0.57:6379 #创建redis cluster集群,与redis5.0集群不同的是,从节点会随机分配给主节点,而非按顺序一一对应
>>> Creating cluster
>>> Performing hash slots allocation on 6 nodes...
Using 3 masters:
10.0.0.7:6379
10.0.0.17:6379
10.0.0.27:6379
Adding replica 10.0.0.47:6379 to 10.0.0.7:6379
Adding replica 10.0.0.57:6379 to 10.0.0.17:6379
Adding replica 10.0.0.37:6379 to 10.0.0.27:6379
M: bf18eec99802798b5215ed2f8ddc12eb1248b3cb 10.0.0.7:6379
   slots:0-5460 (5461 slots) master
M: a0c915ad50c0ad66a0a4c7b6393d9e127576ad64 10.0.0.17:6379
   slots:5461-10922 (5462 slots) master
M: 97b1c4b57dbf5469bab57577f0bc022bd59917e6 10.0.0.27:6379
   slots:10923-16383 (5461 slots) master
S: b18f0f29e766120656abd946b957ef0bd712d638 10.0.0.37:6379
   replicates 97b1c4b57dbf5469bab57577f0bc022bd59917e6
S: fc17f6fea452277328d913324b463a0c91029cd3 10.0.0.47:6379
   replicates bf18eec99802798b5215ed2f8ddc12eb1248b3cb
S: aca9ab569ef599a17449bd2b9088eee4533f515e 10.0.0.57:6379
   replicates a0c915ad50c0ad66a0a4c7b6393d9e127576ad64
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.7:6379)
M: bf18eec99802798b5215ed2f8ddc12eb1248b3cb 10.0.0.7:6379
   slots:0-5460 (5461 slots) master
   1 additional replica(s)
M: 97b1c4b57dbf5469bab57577f0bc022bd59917e6 10.0.0.27:6379
   slots:10923-16383 (5461 slots) master
   1 additional replica(s)
S: aca9ab569ef599a17449bd2b9088eee4533f515e 10.0.0.57:6379
   slots: (0 slots) slave
   replicates a0c915ad50c0ad66a0a4c7b6393d9e127576ad64
S: fc17f6fea452277328d913324b463a0c91029cd3 10.0.0.47:6379
   slots: (0 slots) slave
   replicates bf18eec99802798b5215ed2f8ddc12eb1248b3cb
M: a0c915ad50c0ad66a0a4c7b6393d9e127576ad64 10.0.0.17:6379
   slots:5461-10922 (5462 slots) master
   1 additional replica(s)
S: b18f0f29e766120656abd946b957ef0bd712d638 10.0.0.37:6379
   slots: (0 slots) slave
   replicates 97b1c4b57dbf5469bab57577f0bc022bd59917e6
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.

[19:31:05 root@localhost ~]#redis-cli -a 123456 cluster slots #查看集群主从关系以及槽位信息
Warning: Using a password with '-a' option on the command line interface may not be safe.
1) 1) (integer) 10923
   2) (integer) 16383
   3) 1) "10.0.0.27"
      2) (integer) 6379
      3) "97b1c4b57dbf5469bab57577f0bc022bd59917e6"
   4) 1) "10.0.0.37"
      2) (integer) 6379
      3) "b18f0f29e766120656abd946b957ef0bd712d638"
2) 1) (integer) 0
   2) (integer) 5460
   3) 1) "10.0.0.7"
      2) (integer) 6379
      3) "bf18eec99802798b5215ed2f8ddc12eb1248b3cb"
   4) 1) "10.0.0.47"
      2) (integer) 6379
      3) "fc17f6fea452277328d913324b463a0c91029cd3"
3) 1) (integer) 5461
   2) (integer) 10922
   3) 1) "10.0.0.17"
      2) (integer) 6379
      3) "a0c915ad50c0ad66a0a4c7b6393d9e127576ad64"
   4) 1) "10.0.0.57"
      2) (integer) 6379
      3) "aca9ab569ef599a17449bd2b9088eee4533f515e"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值