Redis集群搭建

原文链接: http://my.oschina.net/ojeta/blog/716545

参考文档: http://redis.io/topics/cluster-tutorial

在6台服务器(192.168.1.121 - 192.168.1.126)上,搭建3主3从集群
官方建议至少3个主,由于redis cluster采取的是数据分片存储,所以为了防止主挂掉,必须给每个主至少分配一个从。故此搭建redis cluster至少是3主3从。

操作系统:CentOS 7

redis下载

http://redis.io/download

解压

mkdir -p /home/redis
tar xf redis-3.0.7.tar.gz
mv redis-3.0.7 redis-cluster

安装

cd redis-cluster
make
make install

会自动将redis-benchmarkredis-check-aofredis-check-dumpredis-cliredis-sentinelredis-server复制到/usr/local/bin中。

创建节点文件夹

在192.168.1.121上

cd /home/redis
mkdir 7001
cp /home/redis/redis-cluster/redis.conf /home/redis/7001

在192.168.1.122上

mkdir 7002
cp /home/redis/redis-cluster/redis.conf /home/redis/7002

在192.168.1.123上

mkdir 7003
cp /home/redis/redis-cluster/redis.conf /home/redis/7003

在192.168.1.124上

mkdir 8001
cp /home/redis/redis-cluster/redis.conf /home/redis/8001

在192.168.1.125上

mkdir 8002
cp /home/redis/redis-cluster/redis.conf /home/redis/8002

在192.168.1.126上

mkdir 8003
cp /home/redis/redis-cluster/redis.conf /home/redis/8003

修改配置文件redis.conf

cd /home/redis/[port]
vi redis.conf

修改redis.conf内容

daemonize yes # 后台启动
pidfile /var/run/redis-[port].pid # 进程号所在文件
logfile /home/redis/[port]/[port].log # 日志文件路径
port [your-port] # 端口
appendonly yes # 开启appendonly模式
cluster-enabled yes # 开启cluster模式
cluster-config-file nodes-[port].conf # 节点配置文件名称
cluster-node-timeout 5000 # 节点心跳超时(毫秒)

启动

cd /home/redis/[port]
redis-server redis.conf

会在当前文件夹下生成

[root@wh-121 7001]# pwd
/home/redis/7001
[root@wh-121 7001]# ll
总用量 52
-rw-r--r--. 1 root root  1522 4月  11 23:43 7001.log
-rw-r--r--. 1 root root     0 4月  11 23:43 appendonly.aof
-rw-r--r--. 1 root root   112 4月  11 23:43 nodes-7001.conf
-rw-r--r--. 1 root root 41672 4月  11 20:52 redis.conf

可能会有警告:

13433:M 10 Apr 23:35:56.904 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
13433:M 10 Apr 23:35:56.904 # Server started, Redis version 3.0.7
13433:M 10 Apr 23:35:56.904 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
13433:M 10 Apr 23:35:56.904 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.

后两个都说的很清楚,解决第1个:echo 511 > /proc/sys/net/core/somaxconn
启动成功会在日志中记录:

4965:M 11 Apr 11:16:06.432 * Increased maximum number of open files to 10032 (it was originally set to 1024).
4965:M 11 Apr 11:16:06.434 * No cluster configuration found, I'm 53c5dedc5aff317d4e1d7b94570bfdee2c54f048
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 3.0.7 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in cluster mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 7001
 |    `-._   `._    /     _.-'    |     PID: 4965
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

4965:M 11 Apr 11:16:06.444 # Server started, Redis version 3.0.7
4965:M 11 Apr 11:16:06.445 * The server is now ready to accept connections on port 7001

停止

redis-cli -c -p [redis-port] shutdown

-c表示集群模式

创建集群

进入任意一台机器的/home/redis/redis-cluster/src/目录

安装ruby
yum install ruby
安装ruby-redis
gem install redis -v 3.0.7

如被墙,可到 https://rubygems.org/gems/redis/ 下,然后执行

gem install redis-3.0.7.gem
创建集群
[root@wh-121 src]# ./redis-trib.rb create --replicas 1 192.168.1.121:7001 192.168.1.122:7002 192.168.1.123:7003 192.168.1.124:8001 192.168.1.125:8002 192.168.1.126:8003

replicas后面的1表示1个主节点对应1个从节点,主节点写前面,从写后面。

Creating cluster
Performing hash slots allocation on 6 nodes...
Using 3 masters:
192.168.1.121:7001
192.168.1.122:7002
192.168.1.123:7003
Adding replica 192.168.1.124:8001 to 192.168.1.121:7001
Adding replica 192.168.1.125:8002 to 192.168.1.122:7002
Adding replica 192.168.1.126:8003 to 192.168.1.123:7003
M: 6a9f161e76708371e887567782f4545e17ae410a 192.168.1.121:7001
   slots:0-5460 (5461 slots) master
M: 6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e 192.168.1.122:7002
   slots:5461-10922 (5462 slots) master
M: 435ee893a3e61d60e286aaf697b1b990b30bff25 192.168.1.123:7003
   slots:10923-16383 (5461 slots) master
S: 31112b04f3b614486c9182701b10065b286f3d8e 192.168.1.124:8001
   replicates 6a9f161e76708371e887567782f4545e17ae410a
S: ad0bebc4185556a8fd93d7e2385d746f622cab26 192.168.1.125:8002
   replicates 6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e
S: aea7fd8077d0735b28759466feb00a46256d2290 192.168.1.126:8003
   replicates 435ee893a3e61d60e286aaf697b1b990b30bff25
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 192.168.1.121:7001)
M: 6a9f161e76708371e887567782f4545e17ae410a 192.168.1.121:7001
   slots:0-5460 (5461 slots) master
M: 6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e 192.168.1.122:7002
   slots:5461-10922 (5462 slots) master
M: 435ee893a3e61d60e286aaf697b1b990b30bff25 192.168.1.123:7003
   slots:10923-16383 (5461 slots) master
M: 31112b04f3b614486c9182701b10065b286f3d8e 192.168.1.124:8001
   slots: (0 slots) master
   replicates 6a9f161e76708371e887567782f4545e17ae410a
M: ad0bebc4185556a8fd93d7e2385d746f622cab26 192.168.1.125:8002
   slots: (0 slots) master
   replicates 6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e
M: aea7fd8077d0735b28759466feb00a46256d2290 192.168.1.126:8003
   slots: (0 slots) master
   replicates 435ee893a3e61d60e286aaf697b1b990b30bff25
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.

节点日志变化,以7001为例:

14645:M 11 Apr 23:48:37.664 # configEpoch set to 1 via CLUSTER SET-CONFIG-EPOCH
14645:M 11 Apr 23:48:37.700 # IP address for this node updated to 192.168.1.121
14645:M 11 Apr 23:48:42.653 # Cluster state changed: ok
14645:M 11 Apr 23:48:43.170 * Slave 192.168.1.124:8001 asks for synchronization
14645:M 11 Apr 23:48:43.170 * Full resync requested by slave 192.168.1.124:8001
14645:M 11 Apr 23:48:43.170 * Starting BGSAVE for SYNC with target: disk
14645:M 11 Apr 23:48:43.170 * Background saving started by pid 14658
14658:C 11 Apr 23:48:43.202 * DB saved on disk
14658:C 11 Apr 23:48:43.202 * RDB: 0 MB of memory used by copy-on-write
14645:M 11 Apr 23:48:43.260 * Background saving terminated with success
14645:M 11 Apr 23:48:43.261 * Synchronization with slave 192.168.1.124:8001 succeeded

在8001:

1981:M 11 Apr 23:48:38.618 # configEpoch set to 4 via CLUSTER SET-CONFIG-EPOCH
1981:M 11 Apr 23:48:38.727 # IP address for this node updated to 192.168.1.124
1981:S 11 Apr 23:48:43.228 # Cluster state changed: ok
1981:S 11 Apr 23:48:44.117 * Connecting to MASTER 192.168.1.121:7001
1981:S 11 Apr 23:48:44.118 * MASTER <-> SLAVE sync started
1981:S 11 Apr 23:48:44.118 * Non blocking connect for SYNC fired the event.
1981:S 11 Apr 23:48:44.119 * Master replied to PING, replication can continue...
1981:S 11 Apr 23:48:44.119 * Partial resynchronization not possible (no cached master)
1981:S 11 Apr 23:48:44.121 * Full resync from master: e095af881f6654216bc0fbc0542b009aaa52fdd0:1
1981:S 11 Apr 23:48:44.210 * MASTER <-> SLAVE sync: receiving 18 bytes from master
1981:S 11 Apr 23:48:44.211 * MASTER <-> SLAVE sync: Flushing old data
1981:S 11 Apr 23:48:44.211 * MASTER <-> SLAVE sync: Loading DB in memory
1981:S 11 Apr 23:48:44.211 * MASTER <-> SLAVE sync: Finished with success
1981:S 11 Apr 23:48:44.219 * Background append only file rewriting started by pid 1992
1981:S 11 Apr 23:48:44.252 * AOF rewrite child asks to stop sending diffs.
1992:C 11 Apr 23:48:44.252 * Parent agreed to stop sending diffs. Finalizing AOF...
1992:C 11 Apr 23:48:44.252 * Concatenating 0.00 MB of AOF diff received from parent.
1992:C 11 Apr 23:48:44.254 * SYNC append only file rewrite performed
1992:C 11 Apr 23:48:44.254 * AOF rewrite: 0 MB of memory used by copy-on-write
1981:S 11 Apr 23:48:44.320 * Background AOF rewrite terminated with success
1981:S 11 Apr 23:48:44.320 * Residual parent diff successfully flushed to the rewritten AOF (0.00 MB)
1981:S 11 Apr 23:48:44.320 * Background AOF rewrite finished successfully

查看集群状态

[root@wh-121 7001]# redis-cli -c -p 7001
127.0.0.1:7001> cluster nodes
ad0bebc4185556a8fd93d7e2385d746f622cab26 192.168.1.125:8002 slave 6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e 0 1460389955802 5 connected
6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e 192.168.1.122:7002 master - 0 1460389956307 2 connected 5461-10922
6a9f161e76708371e887567782f4545e17ae410a 192.168.1.121:7001 myself,master - 0 0 1 connected 0-5460
435ee893a3e61d60e286aaf697b1b990b30bff25 192.168.1.123:7003 master - 0 1460389956307 3 connected 10923-16383
aea7fd8077d0735b28759466feb00a46256d2290 192.168.1.126:8003 slave 435ee893a3e61d60e286aaf697b1b990b30bff25 0 1460389955297 6 connected
31112b04f3b614486c9182701b10065b286f3d8e 192.168.1.124:8001 slave 6a9f161e76708371e887567782f4545e17ae410a 0 1460389954791 4 connected
127.0.0.1:7001> 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_sent:1053
cluster_stats_messages_received:1053
127.0.0.1:7001> 

操作集群

使用任意主节点访问客户端,写数据时会先计算slot编号,然后值会写入相应的slot中,而这个slot可能并不是当前登录节点所在主从服务。最后会自动重定向到slot所在的主节点。

[root@wh-121 src]# redis-cli -c -h 192.168.1.122 -p 7002 # 登录的是7002主节点
192.168.1.122:7002> keys * # 当前节点是空的
(empty list or set)
192.168.1.122:7002> set k v # 插入数据,恰好插入到7002主节点
OK
192.168.1.122:7002> set a b # 插入数据,经计算后得到slot编号不在7002主节点的slot范围内,则重定向到相应的主节点
-> Redirected to slot [15495] located at 192.168.1.123:7003
OK
192.168.1.123:7003> # 当前登录的客户端已改变

数据只会写入到slot所在的主从库中,其它主从服务中无数据,体现了数据的分片

192.168.1.123:7003> keys * # 主7003有数据
1) "a"
192.168.1.123:7003> get a
"b"
[root@wh-121 src]# redis-cli -c -h 192.168.1.126 -p 8003
192.168.1.126:8003> keys * # 主7003的从8003也有数据
1) "a"
192.168.1.126:8003> get a # 取数据的时候从主7003里取
-> Redirected to slot [15495] located at 192.168.1.123:7003
"b"
192.168.1.123:7003> # 并跳到7003

[root@wh-121 7001]# redis-cli -c -h 192.168.1.122 -p 7002
192.168.1.122:7002> keys * # 主7002只有刚才插入的k,没有a
1) "k"
192.168.1.122:7002> get k
"v"
[root@wh-121 7001]# redis-cli -c -p 7001
127.0.0.1:7001> keys * # 主7001无数据
(empty list or set)

故障转移与自动恢复

主节点down掉,对应的从节点自动被选为主

[root@wh-121 7001]# redis-cli -c -p 7001 shutdown
[root@wh-121 7001]# cat 7001.log
...
14645:M 12 Apr 00:02:12.119 # User requested shutdown...
14645:M 12 Apr 00:02:12.119 * Calling fsync() on the AOF file.
14645:M 12 Apr 00:02:12.160 * Saving the final RDB snapshot before exiting.
14645:M 12 Apr 00:02:12.163 * DB saved on disk
14645:M 12 Apr 00:02:12.163 * Removing the pid file.
14645:M 12 Apr 00:02:12.163 # Redis is now ready to exit, bye bye...
[root@wh-124 8001]# cat 8001.log 
...
1981:S 12 Apr 00:02:13.114 # Connection with master lost.
1981:S 12 Apr 00:02:13.114 * Caching the disconnected master state.
1981:S 12 Apr 00:02:13.410 * Connecting to MASTER 192.168.1.121:7001
1981:S 12 Apr 00:02:13.410 * MASTER <-> SLAVE sync started
1981:S 12 Apr 00:02:13.411 # Error condition on socket for SYNC: Connection refused
1981:S 12 Apr 00:02:14.417 * Connecting to MASTER 192.168.1.121:7001
1981:S 12 Apr 00:02:14.417 * MASTER <-> SLAVE sync started
1981:S 12 Apr 00:02:14.417 # Error condition on socket for SYNC: Connection refused
1981:S 12 Apr 00:02:15.424 * Connecting to MASTER 192.168.1.121:7001
1981:S 12 Apr 00:02:15.424 * MASTER <-> SLAVE sync started
1981:S 12 Apr 00:02:15.425 # Error condition on socket for SYNC: Connection refused
1981:S 12 Apr 00:02:16.437 * Connecting to MASTER 192.168.1.121:7001
1981:S 12 Apr 00:02:16.438 * MASTER <-> SLAVE sync started
1981:S 12 Apr 00:02:16.438 # Error condition on socket for SYNC: Connection refused
1981:S 12 Apr 00:02:17.446 * Connecting to MASTER 192.168.1.121:7001
1981:S 12 Apr 00:02:17.446 * MASTER <-> SLAVE sync started
1981:S 12 Apr 00:02:17.448 # Error condition on socket for SYNC: Connection refused
1981:S 12 Apr 00:02:18.453 * Connecting to MASTER 192.168.1.121:7001
1981:S 12 Apr 00:02:18.453 * MASTER <-> SLAVE sync started
1981:S 12 Apr 00:02:18.453 # Error condition on socket for SYNC: Connection refused
1981:S 12 Apr 00:02:19.341 * FAIL message received from 435ee893a3e61d60e286aaf697b1b990b30bff25 about 6a9f161e76708371e887567782f4545e17ae410a
1981:S 12 Apr 00:02:19.341 # Cluster state changed: fail
1981:S 12 Apr 00:02:19.359 # Start of election delayed for 547 milliseconds (rank #0, offset 1121).
1981:S 12 Apr 00:02:19.460 * Connecting to MASTER 192.168.1.121:7001
1981:S 12 Apr 00:02:19.460 * MASTER <-> SLAVE sync started
1981:S 12 Apr 00:02:19.460 # Error condition on socket for SYNC: Connection refused
1981:S 12 Apr 00:02:19.965 # Starting a failover election for epoch 7.
1981:S 12 Apr 00:02:19.983 # Failover election won: I'm the new master.
1981:S 12 Apr 00:02:19.983 # configEpoch set to 7 after successful failover
1981:M 12 Apr 00:02:19.983 * Discarding previously cached master state.
1981:M 12 Apr 00:02:19.984 # Cluster state changed: ok
[root@wh-124 8001]# redis-cli -c -p 8001 # 看到原来的主节点7001显示fail,而8001是主节点
127.0.0.1:8001> cluster nodes
435ee893a3e61d60e286aaf697b1b990b30bff25 192.168.1.123:7003 master - 0 1460390824502 3 connected 10923-16383
31112b04f3b614486c9182701b10065b286f3d8e 192.168.1.124:8001 myself,master - 0 0 7 connected 0-5460
aea7fd8077d0735b28759466feb00a46256d2290 192.168.1.126:8003 slave 435ee893a3e61d60e286aaf697b1b990b30bff25 0 1460390824503 6 connected
6a9f161e76708371e887567782f4545e17ae410a 192.168.1.121:7001 master,fail - 1460390533209 1460390531302 1 disconnected
6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e 192.168.1.122:7002 master - 0 1460390823496 2 connected 5461-10922
ad0bebc4185556a8fd93d7e2385d746f622cab26 192.168.1.125:8002 slave 6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e 0 1460390822486 5 connected

向现在的主节点插入数据,启动之前down掉的主节点,则原来的主节点自动加入集群,并变为从节点,并与现在的主节点同步数据

[root@wh-124 8001]# redis-cli -c -p 8001
127.0.0.1:8001> keys *
(empty list or set)
127.0.0.1:8001> set b d # 插入数据,恰好插入此主节点
OK
127.0.0.1:8001> keys *
1) "b"
127.0.0.1:8001> get b
"d"
[root@wh-121 7001]# redis-server redis.conf # 启动7001
[root@wh-121 7001]# cat 7001.log # 查看7001日志
...
14702:M 12 Apr 00:13:03.335 * The server is now ready to accept connections on port 7001
14702:M 12 Apr 00:13:03.354 # Configuration change detected. Reconfiguring myself as a replica of 31112b04f3b614486c9182701b10065b286f3d8e
14702:S 12 Apr 00:13:03.355 # Cluster state changed: ok
14702:S 12 Apr 00:13:04.360 * Connecting to MASTER 192.168.1.124:8001
14702:S 12 Apr 00:13:04.361 * MASTER <-> SLAVE sync started
14702:S 12 Apr 00:13:04.361 * Non blocking connect for SYNC fired the event.
14702:S 12 Apr 00:13:04.362 * Master replied to PING, replication can continue...
14702:S 12 Apr 00:13:04.363 * Partial resynchronization not possible (no cached master)
14702:S 12 Apr 00:13:04.363 * Full resync from master: c0233be63c5892a289e1886ef799610832ea7a77:1
14702:S 12 Apr 00:13:04.453 * MASTER <-> SLAVE sync: receiving 25 bytes from master
14702:S 12 Apr 00:13:04.454 * MASTER <-> SLAVE sync: Flushing old data
14702:S 12 Apr 00:13:04.454 * MASTER <-> SLAVE sync: Loading DB in memory
14702:S 12 Apr 00:13:04.454 * MASTER <-> SLAVE sync: Finished with success
14702:S 12 Apr 00:13:04.455 * Background append only file rewriting started by pid 14705
14702:S 12 Apr 00:13:04.489 * AOF rewrite child asks to stop sending diffs.
14705:C 12 Apr 00:13:04.489 * Parent agreed to stop sending diffs. Finalizing AOF...
14705:C 12 Apr 00:13:04.489 * Concatenating 0.00 MB of AOF diff received from parent.
14705:C 12 Apr 00:13:04.490 * SYNC append only file rewrite performed
14705:C 12 Apr 00:13:04.491 * AOF rewrite: 0 MB of memory used by copy-on-write
14702:S 12 Apr 00:13:04.563 * Background AOF rewrite terminated with success
14702:S 12 Apr 00:13:04.563 * Residual parent diff successfully flushed to the rewritten AOF (0.00 MB)
14702:S 12 Apr 00:13:04.563 * Background AOF rewrite finished successfully
[root@wh-124 8001]# cat 8001.log # 查看8001日志
1981:M 12 Apr 00:13:04.313 * Clear FAIL state for node 6a9f161e76708371e887567782f4545e17ae410a: master without slots is reachable again.
1981:M 12 Apr 00:13:05.313 * Slave 192.168.1.121:7001 asks for synchronization
1981:M 12 Apr 00:13:05.313 * Full resync requested by slave 192.168.1.121:7001
1981:M 12 Apr 00:13:05.313 * Starting BGSAVE for SYNC with target: disk
1981:M 12 Apr 00:13:05.313 * Background saving started by pid 2028
2028:C 12 Apr 00:13:05.354 * DB saved on disk
2028:C 12 Apr 00:13:05.355 * RDB: 0 MB of memory used by copy-on-write
1981:M 12 Apr 00:13:05.403 * Background saving terminated with success
1981:M 12 Apr 00:13:05.403 * Synchronization with slave 192.168.1.121:7001 succeeded
[root@wh-121 7001]# redis-cli -c -p 7001 # 访问7001客户端
127.0.0.1:7001> keys * # 数据已同步
1) "b"
127.0.0.1:7001> get b
-> Redirected to slot [3300] located at 192.168.1.124:8001
"d"
192.168.1.124:8001> # 跳到主节点
[root@wh-121 7001]# redis-cli -c -p 7001
127.0.0.1:7001> cluster nodes # 查看集群节点信息
6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e 192.168.1.122:7002 master - 0 1460391792446 2 connected 5461-10922
ad0bebc4185556a8fd93d7e2385d746f622cab26 192.168.1.125:8002 slave 6b5b1d9549fd8333cbc566e741fbd0cc08ccff5e 0 1460391792953 5 connected
6a9f161e76708371e887567782f4545e17ae410a 192.168.1.121:7001 myself,slave 31112b04f3b614486c9182701b10065b286f3d8e 0 0 1 connected
435ee893a3e61d60e286aaf697b1b990b30bff25 192.168.1.123:7003 master - 0 1460391791943 3 connected 10923-16383
31112b04f3b614486c9182701b10065b286f3d8e 192.168.1.124:8001 master - 0 1460391792951 7 connected 0-5460
aea7fd8077d0735b28759466feb00a46256d2290 192.168.1.126:8003 slave 435ee893a3e61d60e286aaf697b1b990b30bff25 0 1460391793456 6 connected
```

### 使用Spring Data Redis操作Redis Cluster
#### pom.xml
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>personal.wanghui</groupId>
    <artifactId>quickstart</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>quickstart</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- SpringDataRedis 1.7.1+ 支持Redis集群 -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.7</version>
        </dependency>
    </dependencies>
</project>
```

#### src/main/resources/applicationContext-redis.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:redis="http://www.springframework.org/schema/redis"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/redis
    http://www.springframework.org/schema/redis/spring-redis.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        c:clusterConfig-ref="clusterConfig"
        c:poolConfig-ref="poolConfig" />

    <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
        <constructor-arg name="clusterNodes">
            <util:set>
                <value>192.168.1.121:7001</value>
                <value>192.168.1.122:7002</value>
                <value>192.168.1.123:7003</value>
                <value>192.168.1.124:8001</value>
                <value>192.168.1.125:8002</value>
                <value>192.168.1.126:8003</value>
            </util:set>
        </constructor-arg>
    </bean>

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" 
        p:maxIdle="10" 
        p:minIdle="1" 
        p:testOnBorrow="false" 
        p:testOnReturn="false" 
        p:testWhileIdle="true" />

    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" 
        p:connectionFactory-ref="jedisConnectionFactory" />

</beans>
```

#### 测试类
```java
package personal.wanghui.quickstart;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

public class Main {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-redis.xml");
        StringRedisTemplate stringRedisTemplate = ctx.getBean(StringRedisTemplate.class);
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.set("abc", "def");
        ctx.close();
    }
}
```

#### 执行后的结果
```
[root@wh-121 ~]# redis-cli -c -p 7001
127.0.0.1:7001> keys *
(empty list or set)
127.0.0.1:7001> get abc
-> Redirected to slot [7638] located at 192.168.1.122:7002
"def"
192.168.1.122:7002> 
```

转载于:https://my.oschina.net/ojeta/blog/716545

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值