redis主从复制过程:当配置好slave后,slave与master建立连接,然后发送sync命令。无论是第一次连接还是重新连接,master都会启动一个后台进程,将数据库快照保存到文件中,同时master主进程会开始收集新的写命令并缓存。后台进程完成写文件后,master就发送文件给slave,slave将文件保存到硬盘上,再加载到内存中,接着master就会把缓存的命令转发给slave,后续master将收到的写命令发送给slave。如果master同时收到多个slave发来的同步连接命令,master只会启动一个进程来写数据库镜像,然后发送给所有的slave。
单机上配置实例:
master localhost 6379
slave1 localhost 6378
slave2 localhost 6377
配置:
在2个slave的配置文件中 添加slaveof localhost 6379
分别启动 master slave1 slave2
使用info命令查看各服务器信息
redis 127.0.0.1:6379> info
redis_version:2.4.5
redis_git_sha1:00000000
redis_git_dirty:0
arch_bits:32
multiplexing_api:winsock2
process_id:968
uptime_in_seconds:513
uptime_in_days:0
lru_clock:1957753
used_cpu_sys:0.23
used_cpu_user:0.08
used_cpu_sys_children:0.00
used_cpu_user_children:0.00
connected_clients:1
connected_slaves:2 slave的数目
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0
used_memory:696660
used_memory_human:680.33K
used_memory_rss:696660
used_memory_peak:696628
used_memory_peak_human:680.30K
mem_fragmentation_ratio:1.00
mem_allocator:libc
loading:0
aof_enabled:0
changes_since_last_save:0
bgsave_in_progress:0
last_save_time:1340783219
bgrewriteaof_in_progress:0
total_connections_received:121
total_commands_processed:5
expired_keys:0
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
vm_enabled:0
role:master 说明该服务器为master
redis 127.0.0.1:6378> info
redis_version:2.4.5
redis_git_sha1:00000000
redis_git_dirty:0
arch_bits:32
multiplexing_api:winsock2
process_id:7056
uptime_in_seconds:543
uptime_in_days:0
lru_clock:1957789
used_cpu_sys:0.02
used_cpu_user:0.03
used_cpu_sys_children:0.00
used_cpu_user_children:0.00
connected_clients:2
connected_slaves:0
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0
used_memory:688592
used_memory_human:672.45K
used_memory_rss:688592
used_memory_peak:688560
used_memory_peak_human:672.42K
mem_fragmentation_ratio:1.00
mem_allocator:libc
loading:0
aof_enabled:0
changes_since_last_save:0
bgsave_in_progress:0
last_save_time:1340783116
bgrewriteaof_in_progress:0
total_connections_received:1
total_commands_processed:55
expired_keys:0
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
vm_enabled:0
role:slave
master_host:localhost
master_port:6379
master_link_status:up up说明连接master良好,down则是连接失败
master_last_io_seconds_ago:1
master_sync_in_progress:0
测试:
redis 127.0.0.1:6379> set name wilian
OK
redis 127.0.0.1:6379> get name
"wilian"
redis 127.0.0.1:6378> get name
"wilian"
redis 127.0.0.1:6377> get name
"wilian"
同步成功!