【README】
redis 有3种集群模式,包括 主从, 哨兵, cluster;
本文主要po出 主从;
master 192.168.163.201 6382
slave 192.168.163.202:6382
【1】从机 202:6382 的 redis.conf 配置
只需要编写 slaveof 192.168.163.201 6382 即可
################################# REPLICATION #################################
# Master-Slave replication. Use slaveof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
# 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 slaves.
# 2) Redis slaves 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 slaves automatically try to reconnect to masters
# and resynchronize with them.
#
slaveof 192.168.163.201 6382
【2】 命令行连接到从库
// 连接到从库
[root@centos202 6382]# /usr/local/redis-cluster/bin/redis-cli -h 192.168.163.202 -p 6382
192.168.163.202:6382>
// 查看从库key
192.168.163.202:6382> keys *
1) "balance"
2) "debt"
3) "k1"
// master节点 新增k2后,在从库再次查看key
192.168.163.202:6382> keys *
1) "balance"
2) "debt"
3) "k2"
4) "k1"
192.168.163.202:6382> get k2
"v2"
// 获取 副本信息,很明显, 202:6282是从库;201:6282是主库;
192.168.163.202:6382> info replication
# Replication
role:slave
master_host:192.168.163.201
master_port:6382
master_link_status:up
master_last_io_seconds_ago:9
master_sync_in_progress:0
slave_repl_offset:487
slave_priority:100
slave_read_only:1
connected_slaves:0
master_repl_offset:0
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
【3】把从库变为独立的主库
在客户端执行 slaveof no one
192.168.163.202:6382> slaveof no one
OK
192.168.163.202:6382> info replication
# Replication
role:master
connected_slaves:0
master_repl_offset:543
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
192.168.163.202:6382>
192.168.163.202:6382> keys *
1) "balance"
2) "debt"
3) "k2"
4) "k1"
192.168.163.202:6382> exit
【4】jedis 设置主从
/**
* redis 主从库测试
* @author tr
*/
public class MasterSlaveTest {
public static void main(String[] args) {
Jedis master = new Jedis("192.168.163.201", 6382); // 主库
Jedis slave = new Jedis("192.168.163.202", 6382); // 从库
slave.slaveof("192.168.163.201", 6382); // 设置202 是 201的从库
/* 写入主库 */
master.set("master1", "v1");
/* 从从库读取 */
String result = slave.get("master1");
System.out.println("从库读取的值=" + result);
}
}