1. 程式人生 > >輸出redis cluster 主從的對應關係,如果同一個主從關係的master和slave在同一個node節點上,在輸出的對應關係末尾輸出提示

輸出redis cluster 主從的對應關係,如果同一個主從關係的master和slave在同一個node節點上,在輸出的對應關係末尾輸出提示

 

需求:輸出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

 

測試:

[[email protected] ~]$ 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