如何写巡检Redis连接状态脚本

wen 实用脚本 24

本文目录导读:

如何写巡检Redis连接状态脚本

  1. 示例
  2. 每小时执行并发送报告

我来为您编写一个Redis连接状态巡检脚本,包含多种检测方式:

基础版 - Redis连接检测脚本

#!/bin/bash
# Redis连接状态巡检脚本
# 使用方法: ./check_redis.sh [host] [port] [password]
# 默认配置
REDIS_HOST="${1:-127.0.0.1}"
REDIS_PORT="${2:-6379}"
REDIS_PASSWORD="${3:-}"
LOG_FILE="/var/log/redis_check.log"
DATE_TIME=$(date '+%Y-%m-%d %H:%M:%S')
# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
# 日志函数
log_msg() {
    local level=$1
    local msg=$2
    echo -e "${DATE_TIME} [${level}] ${msg}" >> ${LOG_FILE}
    case $level in
        ERROR)   echo -e "${RED}${msg}${NC}" ;;
        WARNING) echo -e "${YELLOW}${msg}${NC}" ;;
        INFO)    echo -e "${GREEN}${msg}${NC}" ;;
    esac
}
# 检查Redis连接
check_redis_connection() {
    local ping_result
    if [ -z "$REDIS_PASSWORD" ]; then
        ping_result=$(redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT} ping 2>&1)
    else
        ping_result=$(redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT} -a ${REDIS_PASSWORD} ping 2>&1)
    fi
    if [ "$ping_result" = "PONG" ]; then
        log_msg "INFO" "Redis连接正常 - ${REDIS_HOST}:${REDIS_PORT}"
        return 0
    else
        log_msg "ERROR" "Redis连接失败 - ${REDIS_HOST}:${REDIS_PORT} - ${ping_result}"
        return 1
    fi
}
# 获取Redis状态信息
get_redis_info() {
    local info_result
    if [ -z "$REDIS_PASSWORD" ]; then
        info_result=$(redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT} info 2>&1)
    else
        info_result=$(redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT} -a ${REDIS_PASSWORD} info 2>&1)
    fi
    if [ $? -eq 0 ]; then
        echo "$info_result" | grep -E "(connected_clients|used_memory_human|total_connections_received|uptime_in_seconds|role)"
    else
        log_msg "ERROR" "获取Redis状态信息失败"
    fi
}
# 检查关键指标
check_redis_metrics() {
    local metrics
    local connected_clients
    local used_memory
    local uptime
    if [ -z "$REDIS_PASSWORD" ]; then
        metrics=$(redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT} info 2>&1)
    else
        metrics=$(redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT} -a ${REDIS_PASSWORD} info 2>&1)
    fi
    if [ $? -eq 0 ]; then
        connected_clients=$(echo "$metrics" | grep "connected_clients:" | cut -d: -f2)
        used_memory=$(echo "$metrics" | grep "used_memory_human:" | cut -d: -f2)
        uptime=$(echo "$metrics" | grep "uptime_in_seconds:" | cut -d: -f2)
        log_msg "INFO" "连接数: ${connected_clients} | 内存使用: ${used_memory} | 运行时间: ${uptime}秒"
        # 检查连接数是否过高
        if [ ${connected_clients} -gt 1000 ]; then
            log_msg "WARNING" "连接数过高: ${connected_clients}"
        fi
    fi
}
# 主函数
main() {
    log_msg "INFO" "========== Redis连接巡检开始 =========="
    log_msg "INFO" "目标: ${REDIS_HOST}:${REDIS_PORT}"
    # 检查Redis连接
    if check_redis_connection; then
        # 获取状态信息
        get_redis_info
        # 检查关键指标
        check_redis_metrics
    fi
    log_msg "INFO" "========== Redis连接巡检结束 =========="
    echo ""
}
# 执行主函数
main

高级版 - 带邮件告警

#!/bin/bash
# Redis全功能巡检脚本 - 带邮件告警
# 使用方法: ./redis_monitor.sh [host] [port] [password]
# 配置
REDIS_HOST="${1:-127.0.0.1}"
REDIS_PORT="${2:-6379}"
REDIS_PASSWORD="${3:-}"
ALERT_EMAIL="admin@example.com"  # 修改为实际邮箱
MAX_CONNECTIONS=5000
WARN_CONNECTIONS=3000
LOG_DIR="/var/log/redis_monitor"
LOG_FILE="${LOG_DIR}/redis_check_$(date +%Y%m%d).log"
# 创建日志目录
mkdir -p ${LOG_DIR}
# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a ${LOG_FILE}
}
# 发送告警邮件
send_alert() {
    local subject=$1
    local body=$2
    echo "${body}" | mail -s "[Redis Alert] ${subject}" ${ALERT_EMAIL}
    log "已发送告警邮件: ${subject}"
}
# 测试Redis连通性
test_connection() {
    local cmd="redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT}"
    if [ -n "$REDIS_PASSWORD" ]; then
        cmd="${cmd} -a ${REDIS_PASSWORD}"
    fi
    # 测试PING
    if [ "$(${cmd} ping 2>/dev/null)" = "PONG" ]; then
        log "✓ Redis连接测试通过"
        return 0
    else
        log "✗ Redis连接测试失败"
        return 1
    fi
}
# 获取详细信息
get_detailed_info() {
    local cmd="redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT}"
    if [ -n "$REDIS_PASSWORD" ]; then
        cmd="${cmd} -a ${REDIS_PASSWORD}"
    fi
    local info=$(${cmd} info 2>/dev/null)
    log ""
    log "=== Redis状态信息 ==="
    # 服务器信息
    echo "$info" | awk -F: '
        /^redis_version:/ {print "版本: " $2}
        /^os:/ {print "操作系统: " $2}
        /^uptime_in_days:/ {print "运行天数: " $2}
        /^connected_clients:/ {print "当前连接数: " $2}
        /^used_memory_human:/ {print "内存使用: " $2}
        /^total_system_memory_human:/ {print "系统内存: " $2}
        /^used_cpu_sys:/ {print "CPU使用(系统): " $2}
        /^used_cpu_user:/ {print "CPU使用(用户): " $2}
        /^keyspace_hits:/ {print "命中次数: " $2}
        /^keyspace_misses:/ {print "未命中次数: " $2}
        /^role:/ {print "角色: " $2}
    ' | tee -a ${LOG_FILE}
}
# 检查性能指标
check_performance() {
    local cmd="redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT}"
    if [ -n "$REDIS_PASSWORD" ]; then
        cmd="${cmd} -a ${REDIS_PASSWORD}"
    fi
    local info=$(${cmd} info all 2>/dev/null)
    # 检查连接数
    local clients=$(echo "$info" | grep "^connected_clients:" | cut -d: -f2)
    if [ ${clients:-0} -gt ${MAX_CONNECTIONS} ]; then
        send_alert "连接数超限" "当前连接数: ${clients}, 超过最大限制: ${MAX_CONNECTIONS}"
    elif [ ${clients:-0} -gt ${WARN_CONNECTIONS} ]; then
        log "⚠ 连接数警告: ${clients}"
    fi
    # 检查内存使用
    local mem_used=$(echo "$info" | grep "^used_memory_human:" | cut -d: -f2)
    log "内存使用: ${mem_used}"
    # 检查命中率
    local hits=$(echo "$info" | grep "^keyspace_hits:" | cut -d: -f2)
    local misses=$(echo "$info" | grep "^keyspace_misses:" | cut -d: -f2)
    if [ ${misses:-0} -gt 0 ] && [ ${hits:-0} -gt 0 ]; then
        local hit_rate=$(( hits * 100 / (hits + misses) ))
        log "缓存命中率: ${hit_rate}%"
        if [ ${hit_rate} -lt 80 ]; then
            send_alert "缓存命中率低" "当前命中率: ${hit_rate}%"
        fi
    fi
}
# 检查慢查询
check_slow_queries() {
    local cmd="redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT}"
    if [ -n "$REDIS_PASSWORD" ]; then
        cmd="${cmd} -a ${REDIS_PASSWORD}"
    fi
    local slow_log=$(${cmd} slowlog get 10 2>/dev/null)
    if [ -n "$slow_log" ]; then
        local count=$(echo "$slow_log" | grep -c "^1)")
        if [ ${count} -gt 0 ]; then
            log "最近慢查询数: ${count}"
            echo "${slow_log}" >> ${LOG_FILE}
        fi
    fi
}
# 检查持久化
check_persistence() {
    local cmd="redis-cli -h ${REDIS_HOST} -p ${REDIS_PORT}"
    if [ -n "$REDIS_PASSWORD" ]; then
        cmd="${cmd} -a ${REDIS_PASSWORD}"
    fi
    local info=$(${cmd} info persistence 2>/dev/null)
    local rdb_last_save=$(echo "$info" | grep "^rdb_last_save_time:" | cut -d: -f2)
    local aof_enabled=$(echo "$info" | grep "^aof_enabled:" | cut -d: -f2)
    log "RDB最后保存时间: $(date -d @${rdb_last_save:-0} '+%Y-%m-%d %H:%M:%S')"
    log "AOF持久化: $([ "$aof_enabled" = "1" ] && echo '启用' || echo '未启用')"
}
# 主函数
main() {
    log "=========================================="
    log "Redis巡检开始 - 目标: ${REDIS_HOST}:${REDIS_PORT}"
    log "=========================================="
    # 按顺序执行检查
    if test_connection; then
        get_detailed_info
        check_performance
        check_slow_queries
        check_persistence
    fi
    log ""
    log "Redis巡检完成"
    log "=========================================="
    echo ""
}
# 执行主函数
main

使用说明

  1. 基础使用
    # 基本格式
    ./check_redis.sh [host] [port] [password]

示例

./check_redis.sh 127.0.0.1 6379 ./check_redis.sh 192.168.1.100 6379 mypassword


2. **赋予执行权限**:
```bash
chmod +x check_redis.sh
  1. 添加到定时任务(crontab):
    # 每5分钟执行一次
    */5 * * * * /path/to/check_redis.sh 127.0.0.1 6379 >> /var/log/redis_cron.log 2>&1

每小时执行并发送报告

0 /path/to/redis_monitor.sh 127.0.0.1 6379


## 脚本功能说明
- ✅ **连接检测**:PING测试
- ✅ **状态收集**:版本、内存、连接数等
- ✅ **性能监控**:命中率、慢查询
- ✅ **容量检查**:内存使用、连接数
- ✅ **持久化检查**:RDB/AOF状态
- ✅ **告警通知**:邮件告警(高级版)
- ✅ **日志记录**:详细日志输出
这个脚本可以根据您的具体需求进行调整,比如修改告警阈值、添加更多检查项等。

抱歉,评论功能暂时关闭!