Redis搭建一站式教程,单机、主从集群、哨兵集群、分片集群

1、reids安装

  1. 将下载的压缩包解压至需要安装的目录

  2. 启动Redis临时服务
    双击redis安装根路径下的redis-server.exe文件,并保持窗口开启(若关闭窗口则服务关闭)

    [7380] 17 Sep 11:11:40.477 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
    [7380] 17 Sep 11:11:40.477 # Redis version=4.0.2.2, bits=64, commit=00000000, modified=0, pid=7380, just started
    [7380] 17 Sep 11:11:40.477 # Warning: no config file specified, using the default config. In order to specify a config file use e:\environment\redis\redis-server.exe /path/to/redis.conf
                    _._
               _.-``__ ''-._
          _.-``    `.  `_.  ''-._           Redis 4.0.2.2 (00000000/0) 64 bit
      .-`` .-```.  ```\/    _.,_ ''-._
     (    '      ,       .-`  | `,    )     Running in standalone mode
     |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
     |    `-._   `._    /     _.-'    |     PID: 7380
      `-._    `-._  `-./  _.-'    _.-'
     |`-._`-._    `-.__.-'    _.-'_.-'|
     |    `-._`-._        _.-'_.-'    |           http://redis.io
      `-._    `-._`-.__.-'_.-'    _.-'
     |`-._`-._    `-.__.-'    _.-'_.-'|
     |    `-._`-._        _.-'_.-'    |
      `-._    `-._`-.__.-'_.-'    _.-'
          `-._    `-.__.-'    _.-'
              `-._        _.-'
                  `-.__.-'
    
    [7380] 17 Sep 11:11:40.487 # Server initialized
    [7380] 17 Sep 11:11:40.487 * Ready to accept connections
    
  3. 启动Redis客户端测试连接
    双击redis安装根路径下的redis-cli.exe文件,输入 ping命令,测试连接是否成功

    127.0.0.1:6379> ping
    PONG
    127.0.0.1:6379>
    
  4. 安装Redis服务
    在redis安装目录下的地址栏输入cmd直接回车,执行服务安装命令

    E:\environment\redis>redis-server.exe --service-install redis.windows.conf --loglevel verbose
    [13212] 17 Sep 11:21:00.564 # Granting read/write access to 'NT AUTHORITY\NetworkService' on: "E:\environment\redis" "E:\environment\redis\"
    [13212] 17 Sep 11:21:00.564 # Redis successfully installed as a service.
    

    此命令的配置文件参数可以是"redis.windows.conf"或"redis.windows-service.conf"(可以删除一个,两个文件相同)
    执行哪个参数则后期需要修改配置的文件就是哪个
    提示"Redis sucessfully installed as a service."则Redis服务安装成功,可打开任务管理器进行确认
    安装Redis服务后,开机自动 (未修改服务启动方式) 以刚刚配置的redis.con文件启动redis

    在这里插入图片描述

    注:Redis服务安装后默认是开机启动的。如需改为手动启动,右键此电脑,点击"管理",打开"服务",找到Redis,右键点击"属性",修改启动类型为"手动",点击"应用"“确定”,关闭窗口即可。

    卸载redis服务

    redis-server --service-uninstall
    
  5. 修改密码

    redis安装完后,默认是没有密码的。
    使用命令设置的密码为临时密码,重启服务即失效,不推荐;
    推荐修改配置文件设置永久密码,重启服务依旧有效。

    打开安装目录下的redis.windows.conf文件
    搜索"requirepass foobared",在下一行输入"requirepass "+密码,保存后重启服务即可。

    ################################## SECURITY ###################################
    
    # Require clients to issue AUTH <PASSWORD> before processing any other
    # commands.  This might be useful in environments in which you do not trust
    # others with access to the host running redis-server.
    #
    # This should stay commented out for backward compatibility and because most
    # people do not need auth (e.g. they run their own servers).
    #
    # Warning: since Redis is pretty fast an outside user can try up to
    # 150k passwords per second against a good box. This means that you should
    # use a very strong password otherwise it will be very easy to break.
    #
    # requirepass foobared
    
    requirepass 123456
    
  6. 启动redis服务
    启动redis服务:redis-server --service-start (任务管理器选择服务找到Redis右键重新启动。)
    停止redis服务:redis-server --service-stop (任务管理器选择服务找到Redis右键停止。)
    停止指定端口的redis服务:redis-cli -p 6379 shutdown -a 123456

  7. 客户端连接测试

    E:\environment\redis>redis-cli -h 127.0.0.1 -p 6379
    127.0.0.1:6379> auth 1234
    OK
    127.0.0.1:6379> set wu 123456
    OK
    127.0.0.1:6379> get wu
    "123456"
    127.0.0.1:6379>
    

2、reids使用

2.1、服务启动
  1. 若已安装redis服务,并且未修改启动方式,则redis服务开机自启动,可直接登录客户端

  2. 以指定配置文件启动redis服务( 打开dos窗口并切换目录到redis安装路径下 )

    E:\environment\redis\Redis6379>redis-server.exe redis.windows.conf
    [4476] 18 Sep 17:43:04.125 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
    [4476] 18 Sep 17:43:04.125 # Redis version=4.0.2.2, bits=64, commit=00000000, modified=0, pid=4476, just started
    [4476] 18 Sep 17:43:04.125 # Configuration loaded
                    _._
               _.-``__ ''-._
          _.-``    `.  `_.  ''-._           Redis 4.0.2.2 (00000000/0) 64 bit
      .-`` .-```.  ```\/    _.,_ ''-._
     (    '      ,       .-`  | `,    )     Running in standalone mode
     |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
     |    `-._   `._    /     _.-'    |     PID: 4476
      `-._    `-._  `-./  _.-'    _.-'
     |`-._`-._    `-.__.-'    _.-'_.-'|
     |    `-._`-._        _.-'_.-'    |           http://redis.io
      `-._    `-._`-.__.-'_.-'    _.-'
     |`-._`-._    `-.__.-'    _.-'_.-'|
     |    `-._`-._        _.-'_.-'    |
      `-._    `-._`-.__.-'_.-'    _.-'
          `-._    `-.__.-'    _.-'
              `-._        _.-'
                  `-.__.-'
    
    [4476] 18 Sep 17:43:04.125 # Server initialized
    [4476] 18 Sep 17:43:04.125 * DB loaded from disk: 0.000 seconds
    [4476] 18 Sep 17:43:04.125 * Ready to accept connections
    
  3. 以默认配置文件,指定端口启动redis服务

    E:\environment\Redis>redis-server --port 6380
    [18864] 16 Sep 23:14:18.264 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
    [18864] 16 Sep 23:14:18.264 # Redis version=4.0.2.2, bits=64, commit=00000000, modified=0, pid=18864, just started
    [18864] 16 Sep 23:14:18.265 # Configuration loaded
                    _._
               _.-``__ ''-._
          _.-``    `.  `_.  ''-._           Redis 4.0.2.2 (00000000/0) 64 bit
      .-`` .-```.  ```\/    _.,_ ''-._
     (    '      ,       .-`  | `,    )     Running in standalone mode
     |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6380
     |    `-._   `._    /     _.-'    |     PID: 18864
      `-._    `-._  `-./  _.-'    _.-'
     |`-._`-._    `-.__.-'    _.-'_.-'|
     |    `-._`-._        _.-'_.-'    |           http://redis.io
      `-._    `-._`-.__.-'_.-'    _.-'
     |`-._`-._    `-.__.-'    _.-'_.-'|
     |    `-._`-._        _.-'_.-'    |
      `-._    `-._`-.__.-'_.-'    _.-'
          `-._    `-.__.-'    _.-'
              `-._        _.-'
                  `-.__.-'
    
    [18864] 16 Sep 23:14:18.270 # Server initialized
    [18864] 16 Sep 23:14:18.270 * DB loaded from disk: 0.000 seconds
    [18864] 16 Sep 23:14:18.270 * Ready to accept connections
    
2.2、客户端登录
  1. 打开一个 dos窗口,并切换目录到redis安装路径下

    #登录指定ip下指定端口redis
    redis-cli.exe -h 127.0.0.1 -p 6379
    #登录本机下指定端口redis
    redis-cli.exe -p 6379
    
  2. 输入密码

    auth xxxx
    
  3. 登录成功
    在这里插入图片描述
    5.查看当前客户端信息

    127.0.0.1:6379> info replication
    # Replication
    # 当前节点类型,默认为主节点,重新配置除外
    role:master
    # 当前节点连接的从节点个数
    connected_slaves:0
    master_replid:c227d12504ab7d9439dd62d83172d71b8b1fa927
    master_replid2:0000000000000000000000000000000000000000
    master_repl_offset:0
    second_repl_offset:-1
    repl_backlog_active:0
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:0
    repl_backlog_histlen:0
    

    5.退出

    exit
    

3、reids主从复制

3.1、主从复制原理

Redis的主从结构可以采用一主多从或者级联结构,Redis主从复制可以根据是否是全量分为全量同步和增量同步。

全量同步:

Redis全量复制一般发生在Slave初始化阶段,这时Slave需要将Master上的所有数据都复制一份。具体步骤如下:
 1)从服务器连接主服务器,发送SYNC命令;
 2)主服务器接收到SYNC命名后,开始执行BGSAVE命令生成RDB文件并使用缓冲区记录此后执行的所有写命令;
 3)主服务器BGSAVE执行完后,向所有从服务器发送快照文件,并在发送期间继续记录被执行的写命令;
 4)从服务器收到快照文件后丢弃所有旧数据,载入收到的快照;
 5)主服务器快照发送完毕后开始向从服务器发送缓冲区中的写命令;
 6)从服务器完成对快照的载入,开始接收命令请求,并执行来自主服务器缓冲区的写命令;
完成上面几个步骤后就完成了从服务器数据初始化的所有操作,从服务器此时可以接收来自用户的读请求。
在这里插入图片描述

增量同步:

Redis增量复制是指Slave初始化后开始正常工作时主服务器发生的写操作同步到从服务器的过程。
增量复制的过程主要是主服务器每执行一个写命令就会向从服务器发送相同的写命令,从服务器接收并执行收到的写命令。

Redis主从同步策略:

主从刚刚连接的时候,进行全量同步;全同步结束后,进行增量同步。当然,如果有需要,slave 在任何时候都可以发起全量同步。redis 策略是,无论如何,首先会尝试进行增量同步,如不成功,要求从机进行全量同步。

注意:
如果多个Slave断线了,需要重启的时候,因为只要Slave启动,就会发送sync请求和主机全量同步,当多个同时出现的时候,可能会导致Master IO剧增宕机。

3.2、reids 主从集群模式
3.2.1、主从节点切换命令
#将当前节点切换为主节点
slaveof no one
#将当前节点切换为从节点
#slaveof 主节点ip 主节点端口
slaveof 192.168.1.10 6379
3.2.2、主从节点配置
  1. 进入redis安装根目录下

  2. 将redis配置文件redis.windows.conf复制多份(redis.windows-6381.conf,redis.windows-6380.conf)

  3. 修改复制的文件信息

    #从节点端口
    port 6380
    #从节点日志文件
    logfile "redis6380_log.txt"
    #从节点连接的主节点地址端口
    slaveof 127.0.0.1 6379
    #从节点连接的主节点密码
    masterauth 123456
    
  4. 分别启动主从节点服务

    redis-server.exe redis.windows-6380.conf
    redis-server.exe redis.windows-6381.conf
    
  5. 登陆主从客户端

    E:\environment\Redis>redis-cli.exe -h 127.0.0.1 -p 6379
    127.0.0.1:6379> auth 123456
    OK
    127.0.0.1:6379>
    
    E:\environment\Redis>redis-cli.exe -h 127.0.0.1 -p 6380
    127.0.0.1:6380> auth 123456
    OK
    127.0.0.1:6380>
    
    E:\environment\Redis>redis-cli.exe -h 127.0.0.1 -p 6381
    127.0.0.1:6380> auth 123456
    OK
    127.0.0.1:6380>
    
  6. 查看主从节点信息

    127.0.0.1:6379> info replication
    # Replication
    role:master
    connected_slaves:1
    slave0:ip=127.0.0.1,port=6380,state=online,offset=1572,lag=1
    master_replid:8ca67c75418d23299a78137b89720bb822dfd9fd
    master_replid2:0000000000000000000000000000000000000000
    master_repl_offset:1572
    second_repl_offset:-1
    repl_backlog_active:1
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:1
    repl_backlog_histlen:1572
    127.0.0.1:6379>
    
    127.0.0.1:6380> info replication
    # Replication
    role:slave
    master_host:127.0.0.1
    master_port:6379
    master_link_status:up
    master_last_io_seconds_ago:3
    master_sync_in_progress:0
    slave_repl_offset:1614
    slave_priority:100
    slave_read_only:1
    connected_slaves:0
    master_replid:8ca67c75418d23299a78137b89720bb822dfd9fd
    master_replid2:0000000000000000000000000000000000000000
    master_repl_offset:1614
    second_repl_offset:-1
    repl_backlog_active:1
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:99
    repl_backlog_histlen:1516
    127.0.0.1:6380>
    
  7. 主节点写数据,从节点读数据

    127.0.0.1:6379> set zhang 1236987
    OK
    127.0.0.1:6379> get zhang
    "1236987"
    
    127.0.0.1:6380> get zhang
    "1236987"
    127.0.0.1:6380>
    

    注意:从节点默认只读

3、reids 哨兵(sentinel)集群模式

哨兵是Redis的高可用性(High Availability)的解决方案:
由一个或多个sentinel实例组成sentinel集群可以监视一个或多个主服务器和多个从服务器。
当主服务器进入下线状态时,sentinel可以将该主服务器下的某一从服务器升级为主服务器继续提供服
务,从而保证redis的高可用性。

在这里插入图片描述

3.1、哨兵模式的特点:
  1. sentinel模式是建立在主从模式的基础上,如果只有一个Redis节点,sentinel就没有任何意义,
    当master挂了以后,sentinel会在slave中选择一个做为master,并修改它们的配置文件,
    其他slave的配置文件也会被修改,比如slaveof属性会指向新的master
  2. 当master重新启动后,它将不再是master而是做为slave接收新的master的同步数据
  3. sentinel因为也是一个进程有挂掉的可能,所以sentinel也会启动多个形成一个sentinel集群
    多sentinel配置的时候,sentinel之间也会自动监控
  4. 当主从模式配置密码时,sentinel也会同步将配置信息修改到配置文件中,不需要担心
  5. 一个sentinel或sentinel集群可以管理多个主从Redis,多个sentinel也可以监控同一个redis
    sentinel最好不要和Redis部署在同一台机器,不然Redis的服务器挂了以后,sentinel也挂了
3.2、哨兵作用:
  1. 监控:哨兵会不断的检查你的主服务器和从服务器是否运作正常
  2. 通知:当被监控的某个 Redis 服务器出现问题时, 哨兵可以通过API向管理员或者其他应用程序发送通知
  3. 故障迁移:当主服务器不能正常工作时,哨兵会自动进行故障迁移,也就是主从切换
  4. 统一的配置管理:连接者询问哨兵取得主从的地址
3.3、哨兵机制:
  1. 每个sentinel以每秒钟一次的频率向它所知的master,slave以及其他sentinel实例发送一个 PING 命令
  2. 如果一个实例距离最后一次有效回复 PING 命令的时间超过 down-after-milliseconds 选项所指定的值, 则这个实例会被sentinel标记为主观下线。
  3. 如果一个master被标记为主观下线,则正在监视这个master的所有sentinel要以每秒一次的频率确认master的确进入了主观下线状态
  4. 当有足够数量的sentinel(大于等于配置文件指定的值)在指定的时间范围内确认master的确进入了主观下线状态, 则master会被标记为客观下线
  5. 在一般情况下, 每个sentinel会以每 10 秒一次的频率向它已知的所有master,slave发送 INFO 命令
  6. 当master被sentinel标记为客观下线时,sentinel向下线的master的所有slave发送 INFO 命令的频率会从 10 秒一次改为 1 秒一次 若没有足够数量的sentinel同意master已经下线,master的客观下线状态就会被移除;
  7. 若master重新向sentinel的 PING 命令返回有效回复,master的主观下线状态就会被移除
3.1、搭建 reids 哨兵模式(单服务器)

按照上面架构图来搭建架构:一主二从三哨。

  1. 主机:6379
  2. 从机:6380,6381
  3. 哨兵:26379,26380,26381

哨兵模式下的主从配置参考上一节内容。
区别在于:
1、主从节点登陆密码需要设置一样(例如:123456),保障主从自动切换可以连接上新主节点
2、主节点配置需新增一项(masterauth “123456”),用于哨兵故障转移后,原主节点(主节点切换后,自动沦为从节点)能够连上新的主节点

3.2、哨兵配置文件
  1. redis安装目录下有 sentinel.conf(默认端口26379) 文件时,直接修改文件内容,若没有该文件,则新建文件命名为 sentinel.conf。
  2. sentinel.conf 配置样例
    # Example sentinel.conf
     
    # 哨兵sentinel实例运行的端口 默认26379
    port 26379
    
    # 哨兵sentinel的工作目录
    dir "redis安装根目录"
     
    # 哨兵sentinel监控的redis主节点的 ip port 
    # master-name 可以自己命名的主节点名字 只能由字母A-z、数字0-9 、这三个字符".-_"组成。
    # quorum 配置多少个sentinel哨兵统一认为master主节点失联 那么这时客观上认为主节点失联了
    # sentinel monitor <master-name> <ip> <redis-port> <quorum>
    sentinel monitor mymaster 127.0.0.1 6379 2
     
    # 当在Redis实例中开启了requirepass foobared 授权密码 
    # 这样所有连接Redis实例的客户端都要提供密码
    # 设置哨兵sentinel 连接主从的密码 注意必须为主从设置一样的验证密码(例如:123456)
    # sentinel auth-pass <master-name> <password>
    sentinel auth-pass mymaster 123456
     
    # 指定多少毫秒之后 主节点没有应答哨兵sentinel 此时 哨兵主观上认为主节点下线 默认30秒
    # sentinel down-after-milliseconds <master-name> <milliseconds>
    sentinel down-after-milliseconds mymaster 30000
     
    # 这个配置项指定了在发生failover主备切换时最多可以有多少个slave同时对新的master进行同步,
    # 这个数字越小,完成failover所需的时间就越长,
    # 但是如果这个数字越大,就意味着越多的slave因为replication而不可用。
    # 可以通过将这个值设为 1 来保证每次只有一个slave处于不能处理命令请求的状态。
    # sentinel parallel-syncs <master-name> <numslaves>
    sentinel parallel-syncs mymaster 1
     
    # 故障转移的超时时间 failover-timeout 可以用在以下这些方面: 
    # 1. 同一个sentinel对同一个master两次failover之间的间隔时间。
    # 2. 当一个slave从一个错误的master那里同步数据开始计算时间。直到slave被纠正为向正确的master那里同步数据时。
    # 3.当想要取消一个正在进行的failover所需要的时间。  
    # 4.当进行failover时,配置所有slaves指向新的master所需的最大时间。不过,即使过了这个超时,slaves依然会被正确配置为指向master,但是就不按parallel-syncs所配置的规则来了
    # 默认三分钟
    # sentinel failover-timeout <master-name> <milliseconds>
    sentinel failover-timeout mymaster 180000
     
    # SCRIPTS EXECUTION
    # 配置当某一事件发生时所需要执行的脚本,可以通过脚本来通知管理员,例如当系统运行不正常时发邮件通知相关人员。
    # 对于脚本的运行结果有以下规则:
    # 若脚本执行后返回1,那么该脚本稍后将会被再次执行,重复次数目前默认为10
    # 若脚本执行后返回2,或者比2更高的一个返回值,脚本将不会重复执行。
    # 如果脚本在执行过程中由于收到系统中断信号被终止了,则同返回值为1时的行为相同。
    # 一个脚本的最大执行时间为60s,如果超过这个时间,脚本将会被一个SIGKILL信号终止,之后重新执行。
     
    # 1、通知型脚本:
    # 当sentinel有任何警告级别的事件发生时(比如说redis实例的主观失效和客观失效等等),将会去调用这个脚本,这时这个脚本应该通过邮件,SMS等方式去通知系统管理员关于系统不正常运行的信息。
    # 调用该脚本时,将传给脚本两个参数:
    # ※ 事件的类型
    # ※ 事件的描述
    # 如果sentinel.conf配置文件中配置了这个脚本路径,那么必须保证这个脚本存在于这个路径,并且是可执行的,否则sentinel无法正常启动成功。
    # sentinel notification-script <master-name> <script-path>
    # example:sentinel notification-script mymaster /var/redis/notify.sh
     
    # 客户端重新配置主节点参数脚本
    # 当一个master由于failover而发生改变时,这个脚本将会被调用,通知相关的客户端关于master地址已经发生改变的信息。
    # 以下参数将会在调用脚本时传给脚本:
    # <master-name> <role> <state> <from-ip> <from-port> <to-ip> <to-port>
    # 目前<state>总是“failover”,
    # <role>是“leader”或者“observer”中的一个。 
    # 参数 from-ip, from-port, to-ip, to-port是用来和旧的master和新的master(即旧的slave)通信的
    # 这个脚本应该是通用的,能被多次调用,不是针对性的。
    # sentinel client-reconfig-script <master-name> <script-path>
    # sentinel client-reconfig-script mymaster /var/redis/reconfig.sh
    
    #哨兵sentinel实例运行的端口 默认26379
    port 26381
    
    #哨兵sentinel监控的redis主节点的 ip port  
    sentinel monitor mymaster 127.0.0.1 6379 2
    
    #当在Redis实例中开启了requirepass foobared 授权密码 
    sentinel auth-pass mymaster 123456
    
    #指定多少毫秒之后 主节点没有应答哨兵sentinel 此时 哨兵主观上认为主节点下线 默认30秒
    sentinel down-after-milliseconds mymaster 30000
    
    #这个配置项指定了在发生failover主备切换时最多可以有多少个slave同时对新的master进行同步,
    sentinel parallel-syncs mymaster 1
    
3.3、哨兵配置
  1. 将redis复制多份,并修改各自的sentinel.conf 配置文件,(sentinel-26380.conf,sentinel-26381.conf),并修改端口号为文件名称后的数字
  2. 分别启动主从redis服务(启动方式参考上一节内容)
  3. 启动哨兵
    redis-server.exe sentinel.conf --sentinel
    redis-server.exe sentinel-26380.conf --sentinel
    redis-server.exe sentinel-26381.conf --sentinel
    
    E:\environment\redis>redis-server.exe sentinel.conf --sentinel
    [11676] 18 Sep 11:25:41.291 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
    [11676] 18 Sep 11:25:41.291 # Redis version=4.0.2.2, bits=64, commit=00000000, modified=0, pid=11676, just started
    [11676] 18 Sep 11:25:41.291 # Configuration loaded
    [11676] 18 Sep 11:25:41.291 # Windows does not support daemonize. Start Redis as service
                    _._
               _.-``__ ''-._
          _.-``    `.  `_.  ''-._           Redis 4.0.2.2 (00000000/0) 64 bit
      .-`` .-```.  ```\/    _.,_ ''-._
     (    '      ,       .-`  | `,    )     Running in sentinel mode
     |`-._`-...-` __...-.``-._|'` _.-'|     Port: 26379
     |    `-._   `._    /     _.-'    |     PID: 11676
      `-._    `-._  `-./  _.-'    _.-'
     |`-._`-._    `-.__.-'    _.-'_.-'|
     |    `-._`-._        _.-'_.-'    |           http://redis.io
      `-._    `-._`-.__.-'_.-'    _.-'
     |`-._`-._    `-.__.-'    _.-'_.-'|
     |    `-._`-._        _.-'_.-'    |
      `-._    `-._`-.__.-'_.-'    _.-'
          `-._    `-.__.-'    _.-'
              `-._        _.-'
                  `-.__.-'
    
    [11676] 18 Sep 11:25:41.301 # Sentinel ID is 587a2ad868093535b8b2e455d148f7c582e87ac6
    [11676] 18 Sep 11:25:41.301 # +monitor master mymaster 127.0.0.1 6380 quorum 2
    
  4. 查看哨兵状态
    info sentinel
    
    E:\environment\redis>redis-cli -p 26379
    127.0.0.1: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=sdown,address=127.0.0.1:6380,slaves=2,sentinels=3
    
  5. 主节点停止服务,从节点会被提升至主节点,提供写操作
    在这里插入图片描述

4、Cluster集群模式(分片集群)

使用的 Redis 版本为 5.0.14 (5版本以后可以直接使用Redis-cli进行集群的创建和管理,不用重新准备 ruby环境)

redis官方集群文档:http://www.redis.cn/topics/cluster-tutorial.html
cluster模式的出现就是为了解决单机Redis容量有限的问题,将Redis的数据根据一定的规则分配到多台机器。

4.1、分片集群简单理解

我们把集群中的每一个节点当作是一个水桶,而我们的数据只存在其中一个水桶(不用管怎么存怎么取Redis已经做好了),这样当数据越来越多,我们只需要新增“水桶”就好了
因为集群中的每一个服务中的数据都是独一无二的,所以每一个服务需要一个备用服务,也就是主从模式

4.2、分片集群深入理解

Redis 集群没有使用一致性hash, 而是引入了 哈希槽的概念.

Redis 集群有16384个哈希槽,每个key通过CRC16校验后对16384取模来决定放置哪个槽.集群的每个节点负责一部分hash槽,举个例子,比如当前集群有3个节点,那么:

节点 A 包含 0 到 5500号哈希槽
节点 B 包含5501 到 11000 号哈希槽
节点 C 包含11001 到 16384号哈希槽

这种结构很容易添加或者删除节点. 比如如果我想新添加个节点D, 我需要从节点 A, B, C中得部分槽到D上. 如果我想移除节点A,需要将A中的槽移到B和C节点上,然后将没有任何槽的A节点从集群中移除即可. 由于从一个节点将哈希槽移动到另一个节点并不会停止服务,所以无论添加删除或者改变某个节点的哈希槽的数量都不会造成集群不可用的状态

4.2.1、分片集群的主从复制模型

为了使在部分节点失败或者大部分节点无法通信的情况下集群仍然可用,所以集群使用了主从复制模型,每个节点都会有N个复制品

在我们例子中具有A,B,C三个节点的集群,在没有复制模型的情况下,如果节点B失败了,那么整个集群就会以为缺少5501-11000这个范围的槽而不可用

然而如果在集群创建的时候(或者过一段时间)我们为每个节点添加一个从节点A1,B1,C1,那么整个集群便有三个master节点和三个slave节点组成,这样在节点B失败后,集群便会选举B1为新的主节点继续服务,整个集群便不会因为槽找不到而不可用了
不过当B和B1 都失败后,集群是不可用的

4.2.2、分片集群主节点选举原理

从节点的选举和提升都是由从节点处理的,主节点会投票要提升哪个从节点。一个从节点的选举是在主节点被至少一个具有成为主节点必备条件的从节点标记为 FAIL 的状态的时候发生的。

当以下条件满足时,一个从节点可以发起选举:

该从节点的主节点处于 FAIL 状态
这个主节点负责的哈希槽数目不为零
从节点和主节点之间的重复连接(replication link)断线不超过一段给定的时间,这是为了确保从节点的数据是可靠的
一个从节点想要被推选出来,那么第一步应该是提高它的 currentEpoch 计数,并且向主节点们请求投票
从节点通过广播一个 FAILOVER_AUTH_REQUEST 数据包给集群里的每个主节点来请求选票。然后等待回复(最多等 NODE_TIMEOUT 这么长时间)。一旦一个主节点给这个从节点投票,会回复一个 FAILOVER_AUTH_ACK,并且在 NODE_TIMEOUT * 2 这段时间内不能再给同个主节点的其他从节点投票。在这段时间内它完全不能回复其他授权请求。

从节点会忽视所有带有的时期(epoch)参数比 currentEpoch 小的回应(ACKs),这样能避免把之前的投票的算为当前的合理投票。

一旦某个从节点收到了大多数主节点的回应,那么它就赢得了选举。否则,如果无法在 NODE_TIMEOUT 时间内访问到大多数主节点,那么当前选举会被中断并在 NODE_TIMEOUT * 4 这段时间后由另一个从节点尝试发起选举。

一旦有从节点赢得选举,它就会开始用 ping 和 pong 数据包向其他节点宣布自己已经是主节点,并提供它负责的哈希槽,设置 configEpoch 为 currentEpoch(选举开始时生成的)。

4.3、分片集群图

在这里插入图片描述

4.4、分片集群搭建
  1. 创建6个Redis实列(6379,6380,6381,6382,6383,6384),修改相应配置文件内容

    # 只允许使用127.0.0.1继续连接,修改成服务器ip地址
    bind 127.0.0.1 
    # redis实例端口
    port 6379
    # redis以守护进程进行运行(后台运行)
    daemonize yes
    # redis以守护进程进行,会将进程pid号写入pidfile 路径下文件中
    pidfile "redis.pid"
    # redis运行日志
    logfile "redis_log.txt"
    # redis登陆密码
    requirepass 123456
    # redis开启集群
    cluster-enabled yes
    # redis集群配置文件
    cluster-config-file nodes.conf
    # redis集群节点连接超时时间
    cluster-node-timeout 15000
    
  2. 依次启动各个 redis 实例

  3. 创建集群,划分主从节点,并分配槽点

    redis-cli --cluster create 127.0.0.1:6379 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384 --cluster-replicas 1 -a 123456
    

    3台master都已经成功分配了槽位(集群共有16383个槽位可供分配),并且6383是6379的备份,6384是6380的备份,6382是6381的备份,3主3从已经分配好了
    并向你确认是否按照它提供的方案进行分配:输入yes,并回车确认

    E:\environment\redis\Redis-6379>redis-cli --cluster create 127.0.0.1:6379 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384 --cluster-replicas 1 -a 123456
    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 127.0.0.1:6383 to 127.0.0.1:6379
    Adding replica 127.0.0.1:6384 to 127.0.0.1:6380
    Adding replica 127.0.0.1:6382 to 127.0.0.1:6381
    >>> Trying to optimize slaves allocation for anti-affinity
    [WARNING] Some slaves are in the same host as their master
    M: 2938e60f87945a688020740aca51bc0a69090265 127.0.0.1:6379
       slots:[0-5460] (5461 slots) master
    M: 754d6aac1f773f60d73224e0917694ff5a88c91e 127.0.0.1:6380
       slots:[5461-10922] (5462 slots) master
    M: b8624a9bc8d456292aa1550e8c7cb8fc5668a51b 127.0.0.1:6381
       slots:[10923-16383] (5461 slots) master
    S: bb5297743a52e8bd6af779f725a59f1578777d1a 127.0.0.1:6382
       replicates 754d6aac1f773f60d73224e0917694ff5a88c91e
    S: 70abd5c8835adf35ccd430870fd5a2f72467c33e 127.0.0.1:6383
       replicates b8624a9bc8d456292aa1550e8c7cb8fc5668a51b
    S: 1ee75c7a840fad43ebb0a9d1ecb025fff1f0a8f4 127.0.0.1:6384
       replicates 2938e60f87945a688020740aca51bc0a69090265
    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 127.0.0.1:6379)
    M: 2938e60f87945a688020740aca51bc0a69090265 127.0.0.1:6379
       slots:[0-5460] (5461 slots) master
       1 additional replica(s)
    M: b8624a9bc8d456292aa1550e8c7cb8fc5668a51b 127.0.0.1:6381
       slots:[10923-16383] (5461 slots) master
       1 additional replica(s)
    M: 754d6aac1f773f60d73224e0917694ff5a88c91e 127.0.0.1:6380
       slots:[5461-10922] (5462 slots) master
       1 additional replica(s)
    S: bb5297743a52e8bd6af779f725a59f1578777d1a 127.0.0.1:6382
       slots: (0 slots) slave
       replicates 754d6aac1f773f60d73224e0917694ff5a88c91e
    S: 1ee75c7a840fad43ebb0a9d1ecb025fff1f0a8f4 127.0.0.1:6384
       slots: (0 slots) slave
       replicates 2938e60f87945a688020740aca51bc0a69090265
    S: 70abd5c8835adf35ccd430870fd5a2f72467c33e 127.0.0.1:6383
       slots: (0 slots) slave
       replicates b8624a9bc8d456292aa1550e8c7cb8fc5668a51b
    [OK] All nodes agree about slots configuration.
    >>> Check for open slots...
    >>> Check slots coverage...
    [OK] All 16384 slots covered.
    

    显示 [OK] 说明已经按照如上的方案分配完成。

  4. 集群连接
    客户端连接Redis实例操作:

    E:\environment\redis\Redis-6379>redis-cli -h 127.0.0.1 -p 6383 -c
    127.0.0.1:6383> auth 123456
    OK
    127.0.0.1:6383> set bb 123456789
    -> Redirected to slot [8620] located at 127.0.0.1:6380
    (error) NOAUTH Authentication required.
    127.0.0.1:6380> auth 123456
    OK
    127.0.0.1:6380> set bb 123456789
    OK
    127.0.0.1:6380>
    

    连接6379节点,进行一个简单的操作:set bb 123456789
    发现这个简单的命令却被拒绝,提示这个key的数据应该设置到6380这个节点上
    当Redis计算完以后发现这个数据并不属于它所在的槽位,会告诉客户端应该去连6380(若redis未设置密码,就会自动连接,并将数据设置成功)

    127.0.0.1:6383> set bb 123456789
    -> Redirected to slot [8620] located at 127.0.0.1:6380
    (error) NOAUTH Authentication required.
    127.0.0.1:6380> auth 123456
    OK
    127.0.0.1:6380> set bb 123456789
    OK
    127.0.0.1:6380> get aa
    -> Redirected to slot [1180] located at 127.0.0.1:6379
    (error) NOAUTH Authentication required.
    127.0.0.1:6379> auth 123456
    OK
    127.0.0.1:6379> get aa
    "123"
    127.0.0.1:6379>
    

    可以多执行几次命令来看看这个算法,当我们set bb的时候,bb经过计算应该储存到6380这个节点上,所以6383会告诉客户端去连接6380。于是客户端连接6380,并将数据储存到6380。所以此时你get的bb的时候可以直接从6380中取出值。但是此时你再get aa的时候,因为aa储存在6379中,所以6380告诉客户端:我这里面没有aa,你需要去6379中去取aa,所以客户端又会自动到6379中去取得aa的值。

  5. 查看Redis集群的相关命令

    ./redis-cli --cluster help
    
  6. 查看集群状态

    127.0.0.1:6379> 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:218
    cluster_stats_messages_pong_sent:217
    cluster_stats_messages_sent:435
    cluster_stats_messages_ping_received:212
    cluster_stats_messages_pong_received:218
    cluster_stats_messages_meet_received:5
    cluster_stats_messages_received:435
    
  7. 查看集群中的节点

    127.0.0.1:6379> cluster nodes
    b8624a9bc8d456292aa1550e8c7cb8fc5668a51b 127.0.0.1:6381@16381 master - 0 1663858116376 3 connected 10923-16383
    754d6aac1f773f60d73224e0917694ff5a88c91e 127.0.0.1:6380@16380 master - 0 1663858115320 2 connected 5461-10922
    bb5297743a52e8bd6af779f725a59f1578777d1a 127.0.0.1:6382@16382 slave 754d6aac1f773f60d73224e0917694ff5a88c91e 0 1663858114270 4 connected
    1ee75c7a840fad43ebb0a9d1ecb025fff1f0a8f4 127.0.0.1:6384@16384 slave 2938e60f87945a688020740aca51bc0a69090265 0 1663858114000 6 connected
    70abd5c8835adf35ccd430870fd5a2f72467c33e 127.0.0.1:6383@16383 slave b8624a9bc8d456292aa1550e8c7cb8fc5668a51b 0 1663858114000 5 connected
    2938e60f87945a688020740aca51bc0a69090265 127.0.0.1:6379@16379 myself,master - 0 1663858114000 1 connected 0-5460
    
4.4、集群扩容

先创建6385节点 和 6386节点(无数据),扩展一主一从

4.4.1、集群添加6385主节点

启动6385节点服务,并使用如下命令

#6385为新主节点ip端口,6379是任意一个已经存在的节点端口
redis-cli --cluster add-node 127.0.0.1:6385 127.0.0.1:6379
#若节点均设置登陆密码则需要添加 -a 密码
redis-cli --cluster add-node 127.0.0.1:6385 127.0.0.1:6379 -a 123456
E:\environment\redis\Redis-6379>redis-cli --cluster add-node 127.0.0.1:6385 127.0.0.1:6379 -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
>>> Adding node 127.0.0.1:6385 to cluster 127.0.0.1:6379
>>> Performing Cluster Check (using node 127.0.0.1:6379)
M: 2938e60f87945a688020740aca51bc0a69090265 127.0.0.1:6379
   slots:[0-5460] (5461 slots) master
   1 additional replica(s)
S: bb5297743a52e8bd6af779f725a59f1578777d1a 127.0.0.1:6382
   slots: (0 slots) slave
   replicates 754d6aac1f773f60d73224e0917694ff5a88c91e
M: b8624a9bc8d456292aa1550e8c7cb8fc5668a51b 127.0.0.1:6381
   slots:[10923-16383] (5461 slots) master
   1 additional replica(s)
M: 754d6aac1f773f60d73224e0917694ff5a88c91e 127.0.0.1:6380
   slots:[5461-10922] (5462 slots) master
   1 additional replica(s)
S: 1ee75c7a840fad43ebb0a9d1ecb025fff1f0a8f4 127.0.0.1:6384
   slots: (0 slots) slave
   replicates 2938e60f87945a688020740aca51bc0a69090265
S: 70abd5c8835adf35ccd430870fd5a2f72467c33e 127.0.0.1:6383
   slots: (0 slots) slave
   replicates b8624a9bc8d456292aa1550e8c7cb8fc5668a51b
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.
>>> Send CLUSTER MEET to node 127.0.0.1:6385 to make it join the cluster.
[OK] New node added correctly.

执行完毕后,出现如上内容则表示添加成功,可通过 cluster nodes 查看集群节点信息

在这里插入图片描述
添加完主节点需要对主节点进行hash槽分配,这样该主节才可以存储数据。
redis集群有16384个槽,集群中的每个结点分配自已槽,通过查看集群结点可以看到槽占用情况

在这里插入图片描述
给刚添加的6385结点分配槽位

  1. 执行如下命令对6385结点进行槽位分配(其中127.0.0.1:6385是集群里任一节点)

    redis-cli --cluster reshard 127.0.0.1:6385
    
  2. 输入要分配的槽数量, 输入:3000,表示要给目标节点分配3000个槽

    How many slots do you want to move (from 1 to 16384)? 3000
    
  3. 输入接收槽位的结点id (通过cluster nodes查看6385结点id)
    在这里插入图片描述
    在这里插入图片描述

    此处输入all,说明是从所有节点中抽出3000个slots给6385,属于 OUT 操作,
    也可以输入指定的ID(例如6379或6380或6381的ID),可以输入多个,最后输入done结束
    总结 : 如果是新增主节点,输入all即可 ; 如果是移除主节点,需要输入移除的节点ID,再次输入done结束

  4. 输入yes开始移动槽到目标结点id
    在这里插入图片描述

  5. 输入cluster nodes 查看节点信息
    在这里插入图片描述

4.4.2、6386节点设置为6385的从节点

启动6386节点服务,执行如下命令(节点设置密码时,需要在命令最后添加 -a 密码)

#redis-cli --cluster add-node 新节点的ip和端口 主节点ip和端口 --cluster-slave -- cluster-master-id主节点id
redis-cli --cluster add-node 127.0.0.1:6386 127.0.0.1:6385 --cluster-slave --cluster-master-id a826ef43b1bd2d64daf7292aaf68b852fdbf5493 -a 123456
E:\environment\redis\Redis-6379>redis-cli --cluster add-node 127.0.0.1:6386 127.0.0.1:6385 --cluster-slave --cluster-master-id a826ef43b1bd2d64daf7292aaf68b852fdbf5493  -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
>>> Adding node 127.0.0.1:6386 to cluster 127.0.0.1:6385
>>> Performing Cluster Check (using node 127.0.0.1:6385)
M: a826ef43b1bd2d64daf7292aaf68b852fdbf5493 127.0.0.1:6385
   slots:[0-998],[5461-6461],[10923-11921] (2999 slots) master
S: 1ee75c7a840fad43ebb0a9d1ecb025fff1f0a8f4 127.0.0.1:6384
   slots: (0 slots) slave
   replicates 2938e60f87945a688020740aca51bc0a69090265
S: bb5297743a52e8bd6af779f725a59f1578777d1a 127.0.0.1:6382
   slots: (0 slots) slave
   replicates 754d6aac1f773f60d73224e0917694ff5a88c91e
M: 754d6aac1f773f60d73224e0917694ff5a88c91e 127.0.0.1:6380
   slots:[6462-10922] (4461 slots) master
   1 additional replica(s)
M: b8624a9bc8d456292aa1550e8c7cb8fc5668a51b 127.0.0.1:6381
   slots:[11922-16383] (4462 slots) master
   1 additional replica(s)
S: 70abd5c8835adf35ccd430870fd5a2f72467c33e 127.0.0.1:6383
   slots: (0 slots) slave
   replicates b8624a9bc8d456292aa1550e8c7cb8fc5668a51b
M: 2938e60f87945a688020740aca51bc0a69090265 127.0.0.1:6379
   slots:[999-5460] (4462 slots) master
   1 additional replica(s)
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.
>>> Send CLUSTER MEET to node 127.0.0.1:6386 to make it join the cluster.
Waiting for the cluster to join
...
>>> Configure node as replica of 127.0.0.1:6385.
[OK] New node added correctly.

注意:如果原来该结点在集群中的配置信息已经生成到cluster-config-file指定的配置文件中(如果
cluster-config-file没有指定则默认为nodes.conf),这时可能会报错:
[ERR] Node XXXXXX is not empty. Either the node already knows other nodes (check
with CLUSTER NODES) or contains some key in database 0
解决方法是删除生成的配置文件nodes.conf,删除后再执行./redis-cli --cluster add-node 指令

查看集群中的结点,刚添加的6386为6385的从节点

在这里插入图片描述

4.5、集群缩容
4.5.1、移除从节点

redis-cli -a 密码 --cluster del-node 任意节点地址端口 移除的节点地址

E:\environment\redis\Redis-6379>redis-cli --cluster del-node 127.0.0.1:6384 66811444ce334ea583090ab4d841fe973d70c08c -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
>>> Removing node 66811444ce334ea583090ab4d841fe973d70c08c from cluster 127.0.0.1:6384
>>> Sending CLUSTER FORGET messages to the cluster...
>>> SHUTDOWN the node.
4.5.2、移除主节点

移除前需保证该主节点下没有可用槽位,若移除还占有hash槽的结点,则会出现如下错误

E:\environment\redis\Redis-6379>redis-cli --cluster del-node 127.0.0.1:6384 a826ef43b1bd2d64daf7292aaf68b852fdbf5493 -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
>>> Removing node a826ef43b1bd2d64daf7292aaf68b852fdbf5493 from cluster 127.0.0.1:6384
[ERR] Node 127.0.0.1:6385 is not empty! Reshard data away and try again.

将待移除主节点所占有的槽位分配出去(将该节点槽位分配给谁,就对谁进行槽位分配)

  1. 执行如下命令(其中127.0.0.1:6379是集群里任一节点)

    redis-cli -a 123456 --cluster reshard 127.0.0.1:6379
    
  2. 填写需要移动的哈希槽数目

    How many slots do you want to move (from 1 to 16384)? 3000
    
  3. 填写迁入哈希槽的目的节点ID(6379节点id)

    What is the receiving node ID? 2938e60f87945a688020740aca51bc0a69090265
    
  4. 输入迁出哈希槽的源节点ID(6385节点id)【这里可以输入多个节点ID或选择所有节点(all),这里注意源节点ID不能是目的节点ID。】

    Please enter all the source node IDs.
      Type 'all' to use all the nodes as source nodes for the hash slots.
      Type 'done' once you entered all the source nodes IDs.
    Source node #1: a826ef43b1bd2d64daf7292aaf68b852fdbf5493
    Source node #2: done
    
  5. 是否想要根据上面信息制定迁移计划,输入:yes ,接着等待数据迁移完成,至此reshard工作结束

    Do you want to proceed with the proposed reshard plan (yes/no)? yes
    
  6. 查看集群节点信息(此时节点6385已经不占有任何槽位)

    在这里插入图片描述

  7. 移除6385主节点

    E:\environment\redis\Redis-6379>redis-cli -a 123456 --cluster del-node 127.0.0.1:6379 a826ef43b1bd2d64daf7292aaf68b852fdbf5493
    Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
    >>> Removing node a826ef43b1bd2d64daf7292aaf68b852fdbf5493 from cluster 127.0.0.1:6379
    >>> Sending CLUSTER FORGET messages to the cluster...
    >>> SHUTDOWN the node.
    
  8. 此时6385节点就移除完毕

    在这里插入图片描述

4.6、集群停止,重启,新建
  1. 集群停止
    依次停止所有节点服务
  2. 集群重启
    不改变原有集群情况下,只是重启一下,只需要把全部节点服务都关闭,然后再把全部节点服务打开即可。
  3. 新建集群
    • 关闭之前的全部节点
    • 删除节点中的nodes-xxx.conf、dump.rdb、appendonly.aof文件
    • 重启全部的服务
    • 使用上面的命令重新创建集群
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值