Linux-Redis集群狀態監聽腳本


  通過運行Shell腳本達到在裝有redis集群的機器上監聽集群狀態的功能,將監聽結果寫入日志,對於redis地址、監聽周期等實現可配置。

一、原理

  使用Redis客戶端提供的redis-cli命令查詢集群下某個redis節點的狀態,若查詢成功則代表當前該節點是存活狀態,再從該節點向集群進行set值操作,若能成功set值則代表當前節點在所搭建的集群之中。注意僅查詢redis info成功並不能判斷當前節點還在集群之中,還需進行set操作。如此循環掃描集群所有節點。

二、代碼

  

#VERSION="Redis Cluster monitoring version 1.0."


function checkRedis()                                  #定義一個檢查函數
{
    value=`date "+%Y-%m-%d %H:%M:%S"`
    echo "$1 : $2" >>$3
    if ${REDISCLI} -h $1 -p $2 info > /dev/null                  #先檢查當前節點的連接狀態
    then 
        echo "        test connection : success">>$3
        checkset=`${REDISCLI} -h $1 -p $2 -c set CHECK_TIME "${value}"`    #再嘗試在當前節點set值
        if [ "$checkset" == "OK" ]
        then 
            echo "        test operation : success">>$3
        else
            echo "        test operation : failed!!! Message:${checkset}">>$3  
        fi
    else
        echo "        test connection : failed!!!">>$3
    fi
}


r=1
while [ ${r} -ge 0 ]
source /opt/csic/scripts/redis-status.conf                      #引入配置文件
do
DATE=`date "+%Y-%m-%d"`
LogFile=${logDirPath}/redis-status.log_${DATE}
if [ ${Switch} == FALSE ]
then
    echo $(date "+%Y-%m-%d %H:%M:%S %N"|cut -b 1-23) "Monitoring script switch is closed.">>${LogFile}
    sleep ${Cycle}s
elif [ ${Switch} == TRUE ]
then
    echo "########################################################################" >>${LogFile}
    echo $(date "+%Y-%m-%d %H:%M:%S %N"|cut -b 1-23)  "The script starts running.">>${LogFile}
    
    redisCluster=(${RedisCluster//,/ })                        
    redisCount=${#redisCluster[@]}
    for redisNode in ${redisCluster[@]}                        #遍歷節點
    do
        arr=(${redisNode//:/ })                             
        host=${arr[0]}
        port=${arr[1]}
        checkRedis ${host} ${port} ${LogFile}
    done
    sleep ${Cycle}s    
else 
    sleep ${Cycle}s
fi
done

二、配置文件

#!/bin/bash
#VERSION="Redis Cluster monitoring version 1.0."

Switch=TRUE
### scripts switch TRUE or FALSE ###

REDISCLI="/usr/local/bin/redis-cli"
###  redis-cli path ###

logDirPath=/root
### log dir path ###

Cycle=60
###  Check cycle ###

RedisCluster=10.16.8.107:7001,10.16.8.107:7002,10.16.8.107:7003,10.16.8.107:7004,10.16.8.107:7005,10.16.8.107:7006
###  RedisCluster  ###

三、測試

  附一張自測的日志內容:

  其中7003節點不在集群中,7006未啟動。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM