需求:输出redis cluster 主从的对应关系,如果同一个主从关系的master和slave在同一个node节点上,在输出的对应关系末尾输出提示。
为什么会有这样的需求呢?在重新搭建redis cluster的时候,创建集群期间,发现:
redis-trib.rb create --replicas 1 \
5.5.5.101:29001 5.5.5.102:29002 5.5.5.103:29003 \
5.5.5.102:29001 5.5.5.103:29002 5.5.5.101:29003
Adding replica 5.5.5.103:29002 to 5.5.5.103:29003
同一个主从对应关系竟然在同一个节点上了!!!,为了让脚本适应一主多从的关系,这里又在103节点上启动了29005实例并做为29003的slave
cluster nodes信息:
8574f133fd52d32c133245274d027fb90893c524 5.5.5.101:29001@39001 myself,master - 0 1547460560000 1 connected 0-5460 a58667c0738ac2692f7733009d9b44fc6c264721 5.5.5.102:29001@39001 slave 8574f133fd52d32c133245274d027fb90893c524 0 1547460562000 4 connected 86316f44d2b56f7a4fbefd6c5f1594afb928769a 5.5.5.103:29003@39003 master - 0 1547460561000 3 connected 10923-16383 a5d87acb12011b964334bd2bcacf9eb1924c5428 5.5.5.101:29003@39003 slave 98034fcf1d80c7401cafb22775bb70a0c367b91f 0 1547460562768 6 connected b065bd036c1606f52a1a7c2a0936c259ee658799 5.5.5.103:29005@39005 slave 86316f44d2b56f7a4fbefd6c5f1594afb928769a 0 1547460561000 3 connected d6866201dcb87d0383b26de03049cc2be73a0a70 5.5.5.103:29002@39002 slave 86316f44d2b56f7a4fbefd6c5f1594afb928769a 0 1547460561766 5 connected 98034fcf1d80c7401cafb22775bb70a0c367b91f 5.5.5.102:29002@39002 master - 0 1547460563776 2 connected 5461-10922
脚本:
cmd="redis-cli -c -h $1 -p $2" master_id=(`$cmd cluster nodes | grep master | awk '{print $1}'`) master_ip_port=(`$cmd cluster nodes | grep master | awk '$2 ~ /@.*/{gsub("@.*","",$2);print $2}'`) len=${#master_id[@]} for ((i=0;i<=$len-1;i++)); do master_node=$(echo ${master_ip_port[$i]} | awk -F'[:]' '{print $1}') $cmd cluster slaves ${master_id[$i]} | awk '$2 ~ /@.*/{gsub("@.*","",$2);print $2}' > slave_ip_port for j in `cat slave_ip_port` do slave_node=$(echo $j | awk -F'[:]' '{print $1}') if [[ "$master_node" == "$slave_node" ]];then printf "%s%s%s\n" "${master_ip_port[$i]}->" `$cmd cluster slaves ${master_id[$i]} | awk '$2 ~ /@.*/{gsub("@.*","",$2);print $2}' | grep $j` " master和slave在同一个节点上" else printf "%s%s\n" "${master_ip_port[$i]}->" `$cmd cluster slaves ${master_id[$i]} | awk '$2 ~ /@.*/{gsub("@.*","",$2);print $2}' | grep $j` fi done done
测试:
[redis@lxd-vm1 ~]$ sh get_master_slave.sh 5.5.5.101 29001 5.5.5.101:29001->5.5.5.102:29001 5.5.5.103:29003->5.5.5.103:29005 master和slave在同一个节点上 5.5.5.103:29003->5.5.5.103:29002 master和slave在同一个节点上 5.5.5.102:29002->5.5.5.101:29003