本示例使用企业微信的机器人进行告警,可以根据实际情况选择,比如钉钉群组机器人
#!/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin export PATH rm -rf redis_mem.log #设置已使用内存百分比,大于等于该值则告警 #alter_num=14 alter_num=75 redis_ip=$(ip a | grep 192.168 | grep -v secondary | awk '{print $2}' | awk -F'/' '{print $1}') ps -ef |grep redis-server |grep -v grep | awk '$NF~/cluster/{print $(NF-1);next}{print $NF}' |awk -F':' '{print $2}' >redis_ports #printf '%-25s %-10s %-10s %-10s ' redis_ip:port used_memory max_memory used_memory_pct for i in `cat redis_ports` do check_time=$(date +"%F-%T") redis-cli -h $redis_ip -p $i info > info.log used_mem=$(grep -w 'used_memory' info.log | awk -F':' '{print $2}' | sed 's/ //') max_mem=$(grep -w 'maxmemory' info.log | awk -F':' '{print $2}' | sed 's/ //') used_memory_human=$(grep -w 'used_memory_human' info.log | awk -F':' '{print $2}' | sed 's/ //') maxmemory_human=$(grep -w 'maxmemory_human' info.log | awk -F':' '{print $2}' | sed 's/ //') used_memory_pct=$(awk 'BEGIN{printf "%.2f ",('$used_mem'/'$max_mem')*100}') #role=$(grep role info.log | awk -F':' '{print $2}' | sed 's/ //') #printf '%-25s %-10s %-10s %-10s ' $redis_ip:$i $used_memory_human $maxmemory_human $used_memory_pct if [[ $(echo "$used_memory_pct >= $alter_num" | bc) = 1 ]];then #填写自己正确的机器人链接 curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxx' -H 'Content-Type: application/json' -d ' { "msgtype": "text", "text": { "content": "【'$check_time'redis内存告警】 redis实例:'$redis_ip:$i' 最大内存:'$maxmemory_human' 已用内存:'$used_memory_human' 内存使用率:'$used_memory_pct'%", "mentioned_list":["xiaodongl"] } }' fi done
添加crontab定时任务
*/5 * * * * sh /root/redis_scripts/redis_mem_alert.sh &>/dev/null 2>&1
设置告警阈值14%测试