通过运行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  ###

三、测试

  附一张自测的日志内容:

linux查看redis linux查看redis集群状态命令_redis

  其中7003节点不在集群中,7006未启动。