1. 项目背景

1.1 事故回放

周五晚上 11 点,值班群里突然炸了——订单服务大面积超时。值班同学登录数据库看,连接池全满,慢 SQL 刷屏。紧急加了只读副本,降级部分接口,终于在 12 点半稳住。但整整一个半小时没人知道,其实 Redis 在晚上 9 点就已经挂了——主库内存碎片率到 3.0 后 OOM Kill,Sentinel 切到了从库。从库跑了 2 小时后也因相同原因挂了,Redis 彻底不可用。所有请求穿透到数据库,连接池被打满。

如果当时有这三样东西,事故恢复时间可以缩短到 15 分钟:

  1. Redis 节点存活性告警(redis_up == 0)→ 9 点就能发现主库挂了。
  2. 命中率趋势面板 → 9 点发现 hit rate 从 95% 掉到 20%,立刻知道缓存层出了问题。
  3. 碎片率趋势面板 → 下午就能看到碎片率从 1.1 稳定涨到 1.5、2.0、3.0——在 OOM 之前就有几小时的预警窗口。

可观测性(Observability)不是把 INFO 命令的输出变成图表。它要回答三个问题:系统现在是否健康?如果不健康,哪里出了问题?为什么会出这个问题?这对应了监控的三个支柱:指标(Metrics)、追踪(Traces)、日志(Logs)。

对 Redis 来说,最主要的是 Metrics——因为 Redis 已经通过 INFO 命令暴露了大量内部指标,只需要一个 Exporter 把它们转成 Prometheus 格式即可。但光有数据不够,还需要看板(Dashboard)、告警(Alert)、分级处理(SOP)和复盘改进(Postmortem)。

1.2 一个成熟的 Redis 可观测性体系

┌─────────────────────────────────────────────────────────────┐
│                      可观测性四层架构                          │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  第一层:数据采集                                              │
│    INFO → Redis Exporter → Prometheus Pull                   │
│    SLOWLOG → 日志采集 → ELK/Loki                              │
│    LATENCY → Exporter 指标                                   │
│    CLIENT LIST → Exporter 指标                               │
│                                                               │
│  第二层:趋势看板(Grafana)                                   │
│    可用性面板 | 吞吐面板 | 资源面板 | 复制面板 | 集群面板       │
│                                                               │
│  第三层:告警体系                                              │
│    P0 关键告警(主库不可用、集群槽异常)                        │
│    P1 风险告警(内存高、复制断、命中率低)                      │
│    P2 趋势告警(碎片增长、慢查询增加、淘汰增长)                 │
│                                                               │
│  第四层:处理流程                                              │
│    告警 → 值班确认 → SOP 执行 → 止损 → 复盘报告                │
│                                                               │
└─────────────────────────────────────────────────────────────┘

1.3 本章目标

  • 搭建完整的 Redis + Redis Exporter + Prometheus + Grafana 监控栈。
  • 设计一个贴近生产的 Grafana 看板,包含可用性、吞吐、内存、复制、集群五大面板。
  • 配置 12 条分级告警规则(P0/P1/P2),每条都有明确的触发条件、处理人和 SOP。
  • Java 应用中集成 Redis 指标导出到 Micrometer/Prometheus。
  • 编写告警处理 Runbook 和复盘模板。

2. 项目设计

2.1 第一幕:INFO vs Prometheus——不是把黑底白字变彩色

小胖:"INFO 命令输出那么多,我登录上去跑一下不就好了吗?为啥还要费劲搭 Prometheus 和 Grafana?"

大师:"你登录上去只能看到'此刻'的数据。碎片率是从 1.0 涨到 3.0 的——你不能每小时登录一次肉眼对比,但 Grafana 的趋势图一眼就能看到这条曲线在陡升。另外——你在凌晨三点被叫醒处理故障时,是希望先打开 Grafana 看看是哪个指标先异常的,还是希望先敲 10 个 INFO 命令盲猜?"

小白:"而且 INFO 只能看到单机数据。如果你管 20 个 Redis 实例——一个 Sentinel 集群、一个 Cluster 集群、几个独立的缓存实例——你需要一个 dashboard 一眼看到哪些是红的。"

技术映射:INFO 是原始仪表,Prometheus 是记录仪,Grafana 是仪表盘,Alertmanager 是报警器。四个不是互相替代,是流水线。

2.2 第二幕:告警分级——不是越多越好,要让人行动

小胖:"我把所有指标都配上告警——内存超过 60% 就发、命中率低于 99% 就发、连接数多一个就发。这样最安全!"

小白:"第一天你会收到 300 条告警。第二天你会把所有告警静音。第三天你 Redis 挂了但你看不到——因为告警早就被你养成狼来了。"

大师:"告警分级的黄金法则:P0 是'立即行动'——如果不动系统马上不可用;P1 是'安排行动'——有明确风险需要在本值班周期内处理;P2 是'关注趋势'——告警但可以等下一个工作日。每个告警必须有:触发条件、持续时长、影响面、处理 SOP、处理人。"

告警分级示例:

P0(critical)—— 立即处理,不管什么时候
  ├── RedisDown: redis_up == 0 → 主库不可用
  ├── RedisClusterFail: 集群槽位失败
  ├── RedisRejectedConnections: 连接被拒绝(maxclients 满了)
  └── RedisOOMSoon: used_memory > maxmemory * 0.95 且 evicted_keys 增长

P1(warning)—— 本值班周期内处理
  ├── RedisMemoryHigh: 使用率 > 85% 持续 10min
  ├── RedisReplicationBroken: 主从复制断开
  ├── RedisLowHitRate: 命中率 < 80% 持续 10min
  └── RedisEvictionGrowing: 淘汰速率 > 1000/min

P2(info)—— 趋势问题,可以排队处理
  ├── RedisFragGrowing: 碎片率 > 1.5 持续 30min
  ├── RedisSlowlogGrowing: 慢日志条数 > 50
  ├── RedisConnectedTooMany: 连接数 > 500
  └── RedisMasterLastIOSecHigh: 主从延迟 > 10s

技术映射:告警不是"记录所有异常",而是"触发人的行动"。一条好的告警 = 明确的指标异常 + 持续一段时间(for)+ 有 SOP 链接 + 有明确的处理人。

2.3 第三幕:命中率陷阱——数字好看不一定是好事

小胖:"命中率 99%!我们的 Redis 性能好得很。"

大师:"等一下——命中率 99% 是好还是坏?要分场景。如果是一个 10M 大 key 被疯狂访问——命中率 100%,但 Redis 快被你打死了。如果命中率突然从 95% 涨到 100%——不是变好了,可能是新的缓存 key 还没过期,等它们集中过期时雪崩就来。"

小白:"命中率上升也可能是好事——缓存预热成功了,用户能命中更多 key。不能只看一个数字,要结合淘汰数、QPS、数据库压力一起看。"

大师:"对。可观测性的精髓是相关性分析——不是盯着一个指标,而是看多个指标的联动。命中率下降 → 同时看数据库 QPS 是否上升 → 同时看是否有 key 批量过期 → 同时看是否发布了新版本清空了缓存。这才是真正的'观察'。"

命中率分析矩阵:

  命中率 ↓ + 数据库 QPS ↑      → 缓存失效,回源压力大(穿透/雪崩/过期)
  命中率 ↓ + 数据库 QPS 正常    → 可能是新流量打到了新 key(预热未完成)
  命中率 ↓ + 淘汰 keys ↑       → 内存不够,热 key 被淘汰(容量不足)
  命中率 ↓ + 内存使用率 ↓      → 缓存数据被删了(FLUSHDB 或 key 过期)
  命中率 ↑ + 淘汰 keys ↑       → 缓存已经稳定在淘汰后的 hot set
  命中率稳定 + P99 ↑            → 不是命中的问题,可能是热 key/网络/fork

2.4 第四幕:可观测性不是运维专属——开发也要看懂那几条线

小胖:"告警是大盘,开发又不管运维。"

大师:"那你上次发版——改了 key 的序列化格式,所有缓存 miss,打穿数据库。如果你上线前看了一眼命中率面板——从 93% 掉到 6%——你还会说跟你没关系?可观测性的最高境界不是运维收到告警再找你,而是你自己上线后主动去看关键指标。"


3. 项目实战

3.1 环境准备:一键启动监控栈

# 创建项目目录
mkdir redis-monitoring-lab && cd redis-monitoring-lab

# 创建 Docker Compose 文件
cat > docker-compose.yml << 'EOF'
services:
  redis-master:
    image: redis:8.6
    command: ["redis-server", "--appendonly", "yes", "--maxmemory", "256mb", "--maxmemory-policy", "allkeys-lfu"]
    ports:
      - "6379:6379"
    networks:
      - monitoring

  redis-slave:
    image: redis:8.6
    command: ["redis-server", "--appendonly", "yes", "--replicaof", "redis-master", "6379", "--maxmemory", "256mb"]
    ports:
      - "6380:6379"
    networks:
      - monitoring
    depends_on:
      - redis-master

  redis-exporter:
    image: oliver006/redis_exporter:latest
    environment:
      REDIS_ADDR: "redis://redis-master:6379"
      REDIS_EXPORTER_CHECK_KEYS: "test:key1,test:key2"
    ports:
      - "9121:9121"
    networks:
      - monitoring
    depends_on:
      - redis-master

  prometheus:
    image: prom/prometheus:latest
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - ./alert-rules.yml:/etc/prometheus/alert-rules.yml
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.retention.time=15d'
    ports:
      - "9090:9090"
    networks:
      - monitoring

  grafana:
    image: grafana/grafana:latest
    environment:
      GF_SECURITY_ADMIN_USER: admin
      GF_SECURITY_ADMIN_PASSWORD: admin
    ports:
      - "3000:3000"
    networks:
      - monitoring
    volumes:
      - ./grafana-dashboards:/etc/grafana/provisioning/dashboards
      - ./grafana-datasources:/etc/grafana/provisioning/datasources

networks:
  monitoring:
    driver: bridge
EOF

# 创建 Prometheus 配置
cat > prometheus.yml << 'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

alerting:
  alertmanagers:
    - static_configs:
        - targets: []

rule_files:
  - /etc/prometheus/alert-rules.yml

scrape_configs:
  - job_name: 'redis'
    static_configs:
      - targets: ['redis-exporter:9121']
        labels:
          instance: 'redis-master'
          env: 'lab'
EOF

# 启动
docker compose up -d

# 验证
echo "=== 验证 Redis ==="
docker compose exec redis-master redis-cli PING
echo ""
echo "=== 验证 Exporter ==="
curl -s http://localhost:9121/metrics | grep redis_up
echo ""
echo "=== Grafana: http://localhost:3000 (admin/admin) ==="
echo "=== Prometheus: http://localhost:9090 ==="
echo "=== Redis Exporter: http://localhost:9121/metrics ==="

3.2 实战一:理解核心指标

# ========== 可用性指标 ==========
# redis_up: 0 或 1 —— Exporter 能否连上 Redis
curl -s http://localhost:9121/metrics | grep "^redis_up"
# 预期: redis_up 1

# redis_uptime_in_seconds: Redis 运行时长
curl -s http://localhost:9121/metrics | grep "^redis_uptime_in_seconds"

# ========== 连接指标 ==========
# redis_connected_clients: 当前连接数
# redis_blocked_clients: 被阻塞的客户端数(BLPOP 等)
# redis_rejected_connections_total: 累计被拒绝的连接
curl -s http://localhost:9121/metrics | grep -E "redis_connected_clients|redis_blocked|redis_rejected"

# ========== 内存指标 ==========
# redis_memory_used_bytes: 当前使用内存
# redis_memory_max_bytes: maxmemory 设置值
# redis_mem_fragmentation_ratio: 碎片率
curl -s http://localhost:9121/metrics | grep -E "redis_memory|redis_mem_frag"

# ========== 命中率指标 ==========
# redis_keyspace_hits_total: 累计命中次数
# redis_keyspace_misses_total: 累计未命中次数
curl -s http://localhost:9121/metrics | grep -E "redis_keyspace_hits_total|redis_keyspace_misses_total"

# ========== 复制指标 ==========
# redis_connected_slaves: 连接的从库数量
# redis_master_last_io_seconds_ago: 主从延迟(秒)
# redis_master_link_status: 复制链路状态
curl -s http://localhost:9121/metrics | grep -E "redis_connected_slaves|redis_master"

# ========== 命令指标 ==========
# redis_commands_processed_total: 处理命令总数
# redis_instantaneous_ops_per_sec: 瞬间 QPS
curl -s http://localhost:9121/metrics | grep -E "redis_commands_processed_total|redis_instantaneous"

3.3 实战二:制造流量验证面板

# ========== 制造读写流量 ==========

# 写入 500 个 key
for i in $(seq 1 500); do
  docker compose exec redis-master redis-cli SET "product:$i" "value-$i" EX 300 > /dev/null 2>&1
done

# 命中 + 未命中混合
for i in $(seq 1 1000); do
  if [ $((RANDOM % 3)) -eq 0 ]; then
    # 命中
    docker compose exec redis-master redis-cli GET "product:$((RANDOM % 500 + 1))" > /dev/null 2>&1
  else
    # 未命中
    docker compose exec redis-master redis-cli GET "product:$((RANDOM % 5000 + 1000))" > /dev/null 2>&1
  fi
done

# 查看命中率
docker compose exec redis-master redis-cli INFO stats | grep keyspace

3.4 实战三:12 条告警规则

cat > alert-rules.yml << 'EOF'
groups:
  - name: redis_p0
    rules:
      # P0-1: Redis 实例不可用
      - alert: RedisDown
        expr: redis_up == 0
        for: 1m
        labels:
          severity: critical
          team: dba
        annotations:
          summary: "Redis 实例 {{ $labels.instance }} 不可用"
          description: "Redis Exporter 无法连接到 {{ $labels.instance }},请立即检查 Redis 进程是否存活。"
          sop_url: "https://wiki.company.com/redis/down"

      # P0-2: 连接被拒绝(maxclients 满了)
      - alert: RedisRejectedConnections
        expr: increase(redis_rejected_connections_total[5m]) > 0
        for: 1m
        labels:
          severity: critical
          team: dba
        annotations:
          summary: "Redis 拒绝新连接"
          description: "{{ $labels.instance }} 在最近 5 分钟内有连接被拒绝,可能达到 maxclients 上限。"
          sop_url: "https://wiki.company.com/redis/rejected"

      # P0-3: 集群槽位异常
      - alert: RedisClusterSlotsFail
        expr: redis_cluster_slots_fail > 0
        for: 1m
        labels:
          severity: critical
          team: dba
        annotations:
          summary: "Redis Cluster 槽位失败"
          description: "集群 {{ $labels.instance }} 存在失败的槽位,部分 key 不可访问。"

  - name: redis_p1
    rules:
      # P1-1: 内存使用率过高
      - alert: RedisMemoryHigh
        expr: (redis_memory_used_bytes / redis_memory_max_bytes) > 0.85
        for: 5m
        labels:
          severity: warning
          team: dba
        annotations:
          summary: "Redis 内存使用率超过 85%"
          description: "实例 {{ $labels.instance }} 内存使用率 {{ $value | humanizePercentage }},建议检查和扩容。"
          sop_url: "https://wiki.company.com/redis/memory-high"

      # P1-2: 内存使用率危险
      - alert: RedisMemoryCritical
        expr: (redis_memory_used_bytes / redis_memory_max_bytes) > 0.95
        for: 1m
        labels:
          severity: critical
          team: dba
        annotations:
          summary: "Redis 内存使用率超过 95%,即将 OOM!"

      # P1-3: 复制中断
      - alert: RedisReplicationBroken
        expr: redis_connected_slaves < 1
        for: 2m
        labels:
          severity: warning
          team: dba
        annotations:
          summary: "Redis 主从复制中断"
          description: "主库 {{ $labels.instance }} 当前没有连接的从库,高可用降级。"
          sop_url: "https://wiki.company.com/redis/replication-broken"

      # P1-4: 命中率过低
      - alert: RedisLowHitRate
        expr: |
          rate(redis_keyspace_hits_total[5m]) / 
          (rate(redis_keyspace_hits_total[5m]) + rate(redis_keyspace_misses_total[5m])) < 0.80
        for: 10m
        labels:
          severity: warning
          team: app
        annotations:
          summary: "Redis 命中率低于 80%"
          description: "命中率 {{ $value | humanizePercentage }},请检查是否有批量过期、缓存穿透或配置错误。"

      # P1-5: 淘汰速率异常
      - alert: RedisEvictionGrowing
        expr: increase(redis_evicted_keys_total[5m]) > 1000
        for: 5m
        labels:
          severity: warning
          team: dba
        annotations:
          summary: "Redis 每秒淘汰超过 200 个 key"
          description: "淘汰正在加速,可能内存不足或 TTL 策略不合理。"

      # P1-6: 阻塞的客户端
      - alert: RedisBlockedClients
        expr: redis_blocked_clients > 0
        for: 3m
        labels:
          severity: warning
          team: app
        annotations:
          summary: "Redis 存在阻塞客户端"
          description: "{{ $labels.instance }} 有客户端被 BLPOP/BRPOP 等命令阻塞超过 3 分钟。"

  - name: redis_p2
    rules:
      # P2-1: 碎片率偏高
      - alert: RedisFragmentationHigh
        expr: redis_mem_fragmentation_ratio > 1.5
        for: 30m
        labels:
          severity: info
          team: dba
        annotations:
          summary: "Redis 碎片率超过 1.5"
          description: "碎片率 {{ $value }},建议在低峰期执行 MEMORY PURGE。"

      # P2-2: 主从延迟
      - alert: RedisReplicationLag
        expr: redis_master_last_io_seconds_ago > 10
        for: 5m
        labels:
          severity: info
          team: dba
        annotations:
          summary: "Redis 主从延迟超过 10 秒"

      # P2-3: 慢查询过多
      - alert: RedisSlowlogTooMany
        expr: redis_slowlog_length > 50
        for: 5m
        labels:
          severity: info
          team: app
        annotations:
          summary: "Redis 慢日志超过 50 条"
EOF

3.5 实战四:Grafana 面板设计和 PromQL

以下是 Grafana 面板的核心 PromQL 查询:

========== 可用性面板 ==========

实例状态:
  redis_up

========== 吞吐面板 ==========

QPS (瞬时):
  redis_instantaneous_ops_per_sec

QPS 增长速率 (5分钟):
  rate(redis_commands_processed_total[5m])

按命令类型分解 QPS:
  rate(redis_commands_processed_total[5m]) by (cmd)

========== 内存面板 ==========

内存使用率:
  (redis_memory_used_bytes / redis_memory_max_bytes) * 100

内存使用趋势:
  redis_memory_used_bytes

碎片率:
  redis_mem_fragmentation_ratio

key 数量:
  redis_db_keys

淘汰数量增长:
  increase(redis_evicted_keys_total[5m])

========== 缓存面板 ==========

命中率:
  rate(redis_keyspace_hits_total[5m]) / 
  (rate(redis_keyspace_hits_total[5m]) + rate(redis_keyspace_misses_total[5m])) * 100

命中率趋势 (折线图):
  (同上,按时间轴展示)

========== 连接面板 ==========

连接数:
  redis_connected_clients

被阻塞客户端:
  redis_blocked_clients

拒绝连接增长:
  increase(redis_rejected_connections_total[5m])

========== 复制面板 ==========

从库数量:
  redis_connected_slaves

主从延迟:
  redis_master_last_io_seconds_ago

复制偏移差:
  redis_master_repl_offset - on(instance) redis_slave_repl_offset

========== 集群面板(Cluster)==========

集群状态:
  redis_cluster_state  (0=fail, 1=ok)

槽位失败数:
  redis_cluster_slots_fail

已分配槽位:
  redis_cluster_slots_assigned

已知节点数:
  redis_cluster_known_nodes

3.6 实战五:Grafana 数据源和面板配置

# 创建 Grafana 数据源配置
mkdir -p grafana-datasources
cat > grafana-datasources/prometheus.yml << 'EOF'
apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
    editable: true
EOF

# 创建 Grafana 面板配置 (JSON Model)
mkdir -p grafana-dashboards
cat > grafana-dashboards/redis-overview.json << 'JSONEOF'
{
  "apiVersion": 1,
  "providers": [
    {
      "name": "Redis Dashboard",
      "type": "file",
      "updateIntervalSeconds": 30,
      "options": {
        "path": "/etc/grafana/provisioning/dashboards"
      }
    }
  ]
}
JSONEOF

3.7 实战六:Java 应用 Redis 指标接入 Micrometer

@Configuration
public class RedisMicrometerConfig {

    @Bean
    public MeterRegistry meterRegistry() {
        return new SimpleMeterRegistry();
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        LettuceClientConfiguration config = LettuceClientConfiguration.builder()
            .commandTimeout(Duration.ofSeconds(2))
            .build();

        LettuceConnectionFactory factory = new LettuceConnectionFactory(
            new RedisStandaloneConfiguration("localhost", 6379), config);
        factory.setShareNativeConnection(false);
        return factory;
    }

    /**
     * 注册自定义 Redis 指标到 Micrometer
     */
    @Component
    @Slf4j
    public static class RedisMetricsBinder implements MeterBinder {

        private final RedisConnectionFactory connectionFactory;

        public RedisMetricsBinder(RedisConnectionFactory connectionFactory) {
            this.connectionFactory = connectionFactory;
        }

        @Override
        public void bindTo(MeterRegistry registry) {
            // 内存使用率
            Gauge.builder("redis.memory.used_bytes", this, 
                binder -> getInfoMetric("memory", "used_memory"))
                .description("Redis used memory in bytes")
                .register(registry);

            Gauge.builder("redis.memory.max_bytes", this,
                binder -> getInfoMetric("memory", "maxmemory"))
                .register(registry);

            Gauge.builder("redis.memory.frag_ratio", this,
                binder -> {
                    String val = getInfoProperty("memory", "mem_fragmentation_ratio");
                    return val != null ? Double.parseDouble(val) : 1.0;
                })
                .register(registry);

            // 命中率
            Gauge.builder("redis.cache.hit_rate", this, binder -> {
                long hits = getInfoMetric("stats", "keyspace_hits");
                long misses = getInfoMetric("stats", "keyspace_misses");
                long total = hits + misses;
                return total > 0 ? (double) hits / total : 1.0;
            }).register(registry);

            // 连接数
            Gauge.builder("redis.connections", this,
                binder -> getInfoMetric("stats", "connected_clients"))
                .register(registry);

            // 阻塞客户端
            Gauge.builder("redis.blocked_clients", this,
                binder -> getInfoMetric("stats", "blocked_clients"))
                .register(registry);

            // QPS
            Gauge.builder("redis.qps", this,
                binder -> getInfoMetric("stats", "instantaneous_ops_per_sec"))
                .register(registry);
        }

        private long getInfoMetric(String section, String key) {
            try {
                RedisConnection conn = connectionFactory.getConnection();
                Properties props = conn.info(section);
                String value = props.getProperty(key);
                return value != null ? Long.parseLong(value) : 0;
            } catch (Exception e) {
                log.debug("Failed to read Redis metric {}.{}", section, key, e);
                return 0;
            }
        }

        private String getInfoProperty(String section, String key) {
            try {
                RedisConnection conn = connectionFactory.getConnection();
                Properties props = conn.info(section);
                return props.getProperty(key);
            } catch (Exception e) {
                return null;
            }
        }
    }
}

3.8 实战七:Redis 连接池监控

@Component
@Slf4j
public class RedisConnectionPoolMonitor {

    private final RedisConnectionFactory connectionFactory;

    public RedisConnectionPoolMonitor(RedisConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    @Scheduled(fixedRate = 15000)
    public void reportConnectionPoolStats() {
        if (connectionFactory instanceof LettuceConnectionFactory lettuce) {
            try {
                // 注意: Lettuce 连接池需要通过 ClientResources 获取底层指标
                // 以下为获取活跃/空闲连接数的简化实现
                log.debug("Lettuce connection factory active");
                // 生产使用 LettucePoolingConnectionProvider 获取 pool stats
            } catch (Exception e) {
                log.warn("连接池统计异常", e);
            }
        }
    }
}

3.9 实战八:告警处理 SOP 模板

# Redis 告警处理 SOP

## P0-1: RedisDown

**触发条件**: `redis_up == 0` for 1m

**立即动作**(目标 5 分钟内止损):
1. 确认是 Redis 进程挂了还是 Exporter 采集失败。
   - 登录机器: `systemctl status redis` 或 `docker ps | grep redis`
   - 如果 Exporter 挂了,重启 Exporter。
2. 如果是主库挂了 → 确认 Sentinel 是否已完成故障转移。
   - `redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster`
3. 如果故障转移未触发或从库也挂了 → 执行手动切换。
4. 确认应用连接地址是否自动切换到新主库。
5. 通知值班群: "Redis 主库 down, 已切换到从库 xxx, 恢复中"

**根因分析**(30 分钟内):
- 查看系统日志 `dmesg | grep -i oom` 确认是否 OOM Kill
- 查看 Redis 最后的慢日志: `SLOWLOG GET 100`
- 查看最后的 BGSAVE/AOF rewrite 时间

**事后改进**:
- 补充监控告警
- 调整 maxmemory 和淘汰策略
- 增加内存容量或拆分实例

---

## P1-1: RedisMemoryHigh

**触发条件**: 内存使用率 > 85% for 5m

**立即动作**:
1. 登录 Redis 查看: `INFO memory` 和 `MEMORY STATS`
2. 确认是 normal 增长还是突然上涨。
3. 如果突然上涨 → 检查是否有大量新 key 写入(可能是代码 Bug 或攻击)。
4. 如果是正常增长 → 评估是否需要在 24 小时内扩容。

**缓解手段**:
- 调整 maxmemory-policy 为更激进的淘汰策略
- 缩短非关键 key 的 TTL
- 清理大 key

3.10 实战九:自动化巡检脚本

#!/bin/bash
# redis-observability-check.sh —— 每日可观测性巡检

echo "========================================"
echo "  Redis 可观测性巡检 $(date +%Y-%m-%d)"
echo "========================================"

HOST="127.0.0.1"
PORT="6379"

# 1. 检查 Exporter 是否运行
echo ""
echo "[1] Exporter 健康检查"
if curl -s http://localhost:9121/metrics | grep -q "redis_up 1"; then
    echo "  ✓ Exporter 正常, Redis 可达"
else
    echo "  ✗ Exporter 异常或 Redis 不可达!"
fi

# 2. 检查 Prometheus targets
echo ""
echo "[2] Prometheus 目标状态"
curl -s http://localhost:9090/api/v1/targets | \
  python3 -c "import sys,json; data=json.load(sys.stdin); 
  [print(f'  {t[\"labels\"][\"instance\"]}: {t[\"health\"]}') 
   for t in data['data']['activeTargets']]" 2>/dev/null || \
  echo "  请访问 http://localhost:9090/targets 查看"

# 3. 检查告警规则
echo ""
echo "[3] 活跃告警"
curl -s http://localhost:9090/api/v1/alerts | \
  python3 -c "import sys,json; data=json.load(sys.stdin);
  alerts = [a for a in data['data']['alerts'] if a['state']=='firing'];
  if alerts:
    [print(f'  [!] {a[\"labels\"][\"alertname\"]}: {a[\"annotations\"][\"summary\"]}') 
     for a in alerts]
  else:
    print('  无活跃告警')" 2>/dev/null || \
  echo "  请访问 http://localhost:9090/alerts 查看"

# 4. 检查 Redis 核心指标(通过 CLI)
echo ""
echo "[4] Redis 核心指标"
redis-cli -h $HOST -p $PORT INFO stats | grep -E "keyspace_hits|keyspace_misses"
redis-cli -h $HOST -p $PORT INFO memory | grep -E "used_memory_human|mem_fragmentation"
redis-cli -h $HOST -p $PORT INFO replication | grep -E "connected_slaves|master_link_status"

echo ""
echo "========================================"
echo "  巡检完成"
echo "========================================"

3.11 实战十:SLI/SLO 定义和监控

@Component
@Slf4j
public class RedisSliMonitor {

    private final MeterRegistry meterRegistry;

    public RedisSliMonitor(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    /**
     * SLI 定义和采样
     * 
     * 可用性 SLI:     redis_up (目标 99.95%)
     * 延迟 SLI:        P99 < 5ms (目标 99.9%)
     * 命中率 SLI:      > 90% (目标 99% of the time)
     * 主从同步 SLI:    延迟 < 10s
     */

    private volatile long totalRequests = 0;
    private volatile long slowRequests = 0;
    private volatile long failedRequests = 0;

    public void recordRequest(long latencyMs, boolean isError) {
        totalRequests++;
        if (latencyMs > 5) slowRequests++;     // P99 目标 5ms
        if (isError) failedRequests++;

        meterRegistry.timer("redis.request.latency")
            .record(Duration.ofMillis(latencyMs));
    }

    @Scheduled(fixedRate = 60000)
    public void computeAndReportSli() {
        if (totalRequests == 0) return;

        double availability = 1.0 - (double) failedRequests / totalRequests;
        double p99Compliance = 1.0 - (double) slowRequests / totalRequests;

        meterRegistry.gauge("redis.sli.availability", availability);
        meterRegistry.gauge("redis.sli.p99_compliance", p99Compliance);

        // SLO 违规告警
        if (availability < 0.9995) { // 99.95%
            log.warn("[SLI] 可用性 {} < 99.95% SLO", 
                String.format("%.4f", availability));
            meterRegistry.counter("redis.slo.availability_violation").increment();
        }

        if (p99Compliance < 0.999) { // 99.9%
            log.warn("[SLI] P99 达标率 {} < 99.9% SLO", 
                String.format("%.4f", p99Compliance));
            meterRegistry.counter("redis.slo.latency_violation").increment();
        }

        totalRequests = 0;
        slowRequests = 0;
        failedRequests = 0;
    }
}

4. 项目总结

4.1 可观测性成熟度模型

等级 名称 特征 目标
L1 人工巡检 出问题后登录机器看 INFO → L2
L2 基础监控 部署了 Exporter + Prometheus → L3
L3 看板+告警 Grafana 面板 + 分级告警 + SOP → L4
L4 预测性 趋势预测 + 自动扩容 + 故障自愈 → L5
L5 自适应 SLO 驱动 + 自动化运维 + 混沌工程

4.2 关键监控指标速查

类别 指标 PromQL 告警阈值
可用性 redis_up redis_up == 0
内存 使用率 redis_memory_used_bytes / redis_memory_max_bytes > 0.85
碎片 碎片率 redis_mem_fragmentation_ratio > 1.5
命中率 hit/(hit+miss) rate(hits[5m]) / (rate(hits[5m]) + rate(misses[5m])) < 0.80
连接 连接数 redis_connected_clients > 500
连接 拒绝连接 increase(redis_rejected_connections_total[5m]) > 0
阻塞 阻塞客户端 redis_blocked_clients > 0
淘汰 淘汰增长 increase(redis_evicted_keys_total[5m]) > 1000
复制 从库数 redis_connected_slaves < 1
复制 延迟 redis_master_last_io_seconds_ago > 10

4.3 告警分级处理流程

级别 响应时间 通知方式 自动动作 处理人
P0 5 min 电话 + 企业微信 可自动触发故障切换 值班 DBA
P1 30 min 企业微信 无 值班 DBA + 应用开发
P2 下一个工作日 邮件/看板 无 应用开发

4.4 生产事故案例

事故 监控盲区 教训
Redis 挂了半小时无人知 无 redis_up 告警 可用性告警是第一优先级
命中率跌到 20% 没人看 有面板无告警 面板不等于告警,必须有主动通知
碎片率涨到 3.0 后 OOM 只监控了 used_memory 碎片率是独立指标,也要告警
告警收到 300 条/天,全被忽略 告警阈值太敏感 告警分级 + for 持续时间消除抖动
Exporter 挂了导致无告警 没有监控 Exporter 本身 Exporter 的存活性也需要监控

4.5 思考题

  1. 设计题:公司有 20 个 Redis 实例(3 个 Cluster、5 个 Sentinel 组、2 个单机缓存),每个实例的 maxmemory 和业务场景不同。如何设计一套告警规则,使得每个实例的告警阈值都合理,同时又不需要维护 20 份告警规则文件?

  2. 排查题:Grafana 看板显示 Redis 命中率 95%,但应用接口 P99 延迟仍然 200ms。你用 SLOWLOG 只看到每 15 分钟一次 BGSAVE 相关的 80ms 慢查询。但 P99 200ms 显然不应该是每 15 分钟一次的事件导致的。你接下来查什么?

  3. 工程题:你发现凌晨 2 点到 3 点之间,内存使用率从 60% 飙到 85%,然后凌晨 3 点又回到 60%。但 INFO 显示 evicted_keys 没有增长,DBSIZE 也没变化。这 25% 的内存去哪了?如何设计监控来及时发现这种异常?


上一章思考题答案提示(第27章):

第1题(Feed 流优化方案):方案 A:用 LRANGE 0 99 + LTRIM 0 999——分页返回最近 100 条,超过 1000 条自动截断,冷数据归档到 MongoDB/HBase。优点:改动最小,内存可控;缺点:只能看最近 1000 条。方案 B:把时间线拆成按日期分片的 List——feed:timeline:user:10086:20260701、feed:timeline:user:10086:20260702...每次查询只读最近 3 天的 List。优点:支持更长的历史、天然分片;缺点:跨天查询需要合并多个 List。方案 C:用 Sorted Set 存储,score 为时间戳,ZREVRANGEBYSCORE 按时间窗口查询。优点:灵活的时间范围查询;缺点:内存占用更高。

第2题(CPU 80% 但无慢命令):虽然每个 GET 只要 8μs,但 80000 × 8μs = 640ms/秒的纯计算时间。加上系统调用、网络 I/O、上下文切换——单核 CPU 实际消耗已经超过 60%。80000 QPS 的 GET 本身就是瓶颈。优化方向:① 用 Pipeline 合并请求,减少 RTT 和解析开销;② 开多个 Redis 实例分担 CPU;③ 如果 QPS 必须降,考虑用本地缓存(Caffeine)减少 50-80% 的 Redis 请求。

第3题(dictFind + getExpire 高 CPU):dictFind 是 Hash 表查找,getExpire 是过期字典查找。两者合计 45% CPU 说明 Redis 在大量执行 key 查找和过期判断。可能原因:① key 数量巨大(千万级)导致 Hash 表碰撞增加;② 大量 key 设置了 TTL,过期检查(active expire cycle)频繁触发;③ rehash 正在进行中。定位方法:DBSIZE 看 key 数量,INFO stats 看 expired_keys 确认过期速率,MEMORY STATS 看 overhead.hashtable 确认主字典开销。

延伸阅读与资源

Redis 8 实战精讲:从 CRUD 到源码,构建高可用缓存系统
Java 工程师进阶:从 JVM 生产排障到OpenJDK原理
MySQL Server 9从入门到进阶的实战之旅
Nacos 3.x 注册配置中心实战修炼:从入门到源码扩展
Elasticsearch从入门到进阶的实战之旅
RabbitMQ从入门到进阶的实战之旅:从单机到大促高可用架构
Celery 入门到进阶之路:从异步任务到自研调度平台
LangGraph 生产级实战进阶:从零到生产级Agent工作流开发
Dify 从入门到源码:LLM 应用平台实战修炼
从零到生产级:FastAPI 异步高并发、源码与 SRE 实战
实战SQLAlchemy 2.0: 从 CRUD 到生产级架构
从零打造企业级 AI 助手:LangChain RAG、Agent 与生产实战
后端工程师 AI 转型课:Ollama 私有化大模型从入门到生产
MongoDB 实战进阶与内核修炼
NumPy 从入门到生产落地:全链路实战指南(科学计算/向量化/性能调优)
Milvus向量数据库实战修炼:从 0 到 1 精通向量检索与生产落地
Python 3实战精进:从脚本到高并发订单引擎
python入门:Rquests从菜鸟脚本到企业级SDK的网络实战圣经

posted on 2026-11-25 10:26  一天不进步,就是退步  阅读(15)  评论(0)    收藏  举报