即使有了主从复制,每个数据库都要保存整个集群中的所有数据,容易形成木桶效应。Redis3.0版本的一大特性就是集群(Cluster),接下来我们一起学习集群。
1.添加6479,6480,6481三个端口(可以参考我的另一篇博客redis主从复制)
2.在redis.conf配置文件中,开启集群,cluster-enabledyes
3.指定集群的配置文件,cluster-config-file"nodes-xxxx.conf"
4.创建集群
4.1环境安装(ruby)
因为redis-trib.rb是有ruby语言编写的所以需要安装ruby环境。
yum -y install zlib ruby rubygems
gem install redis
手动安装:
rz上传redis-3.2.1.gem
gem install -l redis-3.2.1.gem
4.2 创建集群
首先,进入redis的安装包路径下:cd /usr/local/src/redis/redis-3.0.2
[root@localhost src]# ls
adlist.c crc64.h mkreleasehdr.sh redis-cli.c sort.o
adlist.h crc64.o multi.c redis-cli.o sparkline.c
adlist.o db.c multi.o redis.h sparkline.h
ae.c db.o networking.c redis.o sparkline.o
ae_epoll.c debug.c networking.o redis-sentinel syncio.c
ae_evport.c debug.o notify.c redis-server syncio.o
ae.h dict.c notify.o redis-trib.rb testhelp.h
ae_kqueue.c dict.h object.c release.c t_hash.c
ae.o dict.o object.o release.h t_hash.o
ae_select.c endianconv.c pqsort.c release.o t_list.c
anet.c endianconv.h pqsort.h replication.c t_list.o
anet.h endianconv.o pqsort.o replication.o t_set.c
anet.o fmacros.h pubsub.c rio.c t_set.o
aof.c help.h pubsub.o rio.h t_string.c
aof.o hyperloglog.c rand.c rio.o t_string.o
asciilogo.h hyperloglog.o rand.h scripting.c t_zset.c
bio.c intset.c rand.o scripting.o t_zset.o
bio.h intset.h rdb.c sds.c util.c
bio.o intset.o rdb.h sds.h util.h
bitops.c latency.c rdb.o sds.o util.o
bitops.o latency.h redisassert.h sentinel.c valgrind.sup
blocked.c latency.o redis-benchmark sentinel.o version.h
blocked.o lzf_c.c redis-benchmark.c setproctitle.c ziplist.c
执行命令: ./redis-trib.rb create --replicas 0 192.168.2.86:6479192.168.2.86:6480 192.168.2.86:6481 之后输入yes确认
--replicas 0:指定了从数据的数量为0
注意:这里不能使用127.0.0.1,否则在Jedis客户端使用时无法连接到!
(不好意思啊,因为我已经装好了,所以借用了一下网上的图)
4.3 测试
[root@localhost /]# redis-cli
Could not connect to Redis at 127.0.0.1:6379: Connection refused
not connected>
这里请注意,如果你完全按照我的步骤来的,直接输入redis-cli是不行的,它默认是6379,所以你得输入redis-cli -p 6479
127.0.0.1:6479> set abc 123
(error) MOVED 7638 192.168.2.86:6480
127.0.0.1:6479>
因为abc的hash槽信息是在6480上,现在使用redis-cli连接的6479,无法完成set操作,需要客户端跟踪重定向。
redis-cli -c -p 6479
[root@localhost /]# redis-cli -c -p 6479
127.0.0.1:6479> set abc 123
-> Redirected to slot [7638] located at 192.168.2.86:6480
OK
192.168.2.86:6480>
这里它由6479跳到6480了,我们回到6479看下有没有abc的数据
[root@localhost /]# redis-cli -c -p 6479
127.0.0.1:6479> get abc
-> Redirected to slot [7638] located at 192.168.2.86:6480
"123"
192.168.2.86:6480>
依然重定向到6480,不过已经能够得到数据了
在这里需要解释下,它重定向到6480,是因为设置abc的值时,首先计算了abc的插槽值,它是在6480端口的插槽值之间的