Redis单机版搭建上一篇已经基本介绍了,下面讨论Redis集群搭建方案和示例。
1、关于Redis常用的集群方案(三种):
a、一主多从,如一个Master、两个Slave
b、薪火相传,即集群中的从节点(Slave)同时也是主节点(Master),类似于链式传递一样
c、反客为主,主节点down掉后从节点升级为主节点,通过人工干预 或者 通过Sentinel 哨兵模式来实现(下篇介绍)
2、模拟测试(以一主多从为例)
模拟主机信息(在同一台主机通过不同端口模拟):
角色 | IP | 端口 |
Master | 127.0.0.1 | 6379 |
Salve | 127.0.0.1 | 6380 |
Salve | 127.0.0.1 | 6381 |
进入Redis目录,复制redis配置文件,给Slave使用:
1 [root@VM_0_14_centos redis]# ls -lrt 2 total 12700 3 -rwxr-xr-x 1 root root 8100759 Mar 20 16:12 redis-server 4 -rwxr-xr-x 1 root root 4805624 Mar 20 16:13 redis-cli 5 -rw-r--r-- 1 root root 62156 Mar 20 17:17 redis.conf 6 [root@VM_0_14_centos redis]# cp redis.conf ./redis.6380.conf 7 [root@VM_0_14_centos redis]# cp redis.conf ./redis.6381.conf 8 [root@VM_0_14_centos redis]#
编辑Master配置文件redis.conf文件,主要配置以下参数:
daemonize yes #开启守护进程
pidfile /var/run/redis_6379.pid #开启守护进程后会将进程ID写入该文件
logfile "/var/log/redis.6379.log" #配置日志文件
masterauth funnyboy0128 #master验证密码
requirepass funnyboypass #Redis登录密码
编辑Slave配置文件redis.6380.conf 和redis.6381.conf ,修改pidfile和logfile的值,并在最后追加 slaveof 配置项,修改端口分贝为6380和6380
port 6380 和 port 6381
slaveof 127.0.0.1 6379 #Master的I配合端口
启动Master节点:
1 [root@VM_0_14_centos redis]# 2 [root@VM_0_14_centos redis]# 3 [root@VM_0_14_centos redis]# 4 [root@VM_0_14_centos redis]# ./redis-server ./redis.conf
启动Slave节点:
1 [root@VM_0_14_centos redis]# 2 [root@VM_0_14_centos redis]# 3 [root@VM_0_14_centos redis]# ./redis-server ./redis.6380.conf 4 [root@VM_0_14_centos redis]# ./redis-server ./redis.6381.conf 5 [root@VM_0_14_centos redis]#
客户端连接测试:
1 [root@VM_0_14_centos redis]# 2 [root@VM_0_14_centos redis]# ./redis-cli -h 127.0.0.1 -p 6379 -a funnyboypass 3 Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe. 4 127.0.0.1:6379> keys * 5 (empty list or set) 6 127.0.0.1:6379> set name hello redis 7 (error) ERR syntax error 8 127.0.0.1:6379> set name "hello redis" 9 OK 10 127.0.0.1:6379> 11 127.0.0.1:6379> 12 127.0.0.1:6379> get name 13 "hello redis" 14 127.0.0.1:6379>
连接Master,set信息到Redis。然后连接Slave查看数据,
1 [root@VM_0_14_centos redis]# 2 [root@VM_0_14_centos redis]# ./redis-cli -h 127.0.0.1 -p 6380 -a funnyboypass 3 Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe. 4 127.0.0.1:6380> 5 127.0.0.1:6380> 6 127.0.0.1:6380> 7 127.0.0.1:6380> get name 8 "hello redis" 9 127.0.0.1:6380>
6380 Slave节点数据OK。
1 [root@VM_0_14_centos redis]# ./redis-cli -h 127.0.0.1 -p 6381 -a funnyboypass 2 Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe. 3 127.0.0.1:6381> get name 4 "hello redis" 5 127.0.0.1:6381> 6 127.0.0.1:6381>
测试Slave是否支持写入:
1 127.0.0.1:6381> 2 127.0.0.1:6381> set sname hello 3 (error) READONLY You can't write against a read only replica. 4 127.0.0.1:6381>
结果显示Slave值只支持读操作。