启用lettuce内置指标需配置spring.redis.lettuce.metrics.enabled=true,否则redis.command.latency.*等指标为0;仅sync命令被统计,异步/响应式调用不计入;连接池指标需显式注册poolmeterbinder;命中率与错误率须通过info stats手动计算。

启用 Lettuce 内置指标必须配 spring.redis.lettuce.metrics.enabled=true
Spring Boot 默认完全不采集 Redis 命令耗时,哪怕你已经引入 micrometer-registry-prometheus 并暴露了 /actuator/prometheus 端点,redis.command.latency.count 这类指标依然为 0。根本原因是 Lettuce 的指标挂钩默认关闭,且 Spring Boot 不会自动装配 RedisMeterRegistry(3.2+ 已弃用)。唯一可靠路径是显式开启 Lettuce 自带的 Micrometer 集成:
- 确保使用 Lettuce(Spring Boot 2.7+ 默认客户端),Jedis 不支持此机制
- 在
application.yml中添加:spring: redis: lettuce: metrics: enabled: true - 不需要额外写
@Bean,Spring Boot 会自动注册LettuceClientResources并绑定RedisCommandLatencyMetrics
redis.command.latency.* 指标只统计同步命令,异步/响应式调用不计入
这些指标(如 redis.command.latency.count、redis.command.latency.sum)仅由 Lettuce 的 StatefulRedisConnection.sync() 调用触发。如果你用的是 reactiveRedisTemplate 或手动调用 connection.async().get(...),耗时不会被记录——这是线上排查“监控数据偏低”时最常踩的坑。
- 验证方式:curl
/actuator/prometheus搜索redis_command_latency,确认有非零值;再查业务代码是否混用了 sync/async - 若必须监控响应式链路,需自行用
MeterRegistry.timer()包裹关键操作,不能依赖内置指标 - 命令名按 Redis 协议标准化(
GET、SET、HGETALL),大小写敏感,不包含参数或 key 名
连接池指标要单独注册 PoolMeterBinder,否则 redis.connection.pool.* 为空
即使启用了 Lettuce 指标,redis.connection.pool.idle、redis.connection.pool.active 这类连接池指标也不会自动出现。因为 Lettuce 底层用的是 Apache Commons Pool2,其指标需显式绑定到 MeterRegistry。
- 在配置类中声明 Bean:
@Bean public PoolMeterBinder poolMeterBinder(GenericObjectPool<redischannelhandler> pool, MeterRegistry registry) { return new PoolMeterBinder(pool, "redis.connection.pool", registry); }</redischannelhandler> - 注意泛型类型必须匹配实际连接池(
GenericObjectPool<redischannelhandler></redischannelhandler>是 Lettuce 4.x+ 的典型类型) - 若用自定义连接池配置(如调整
max-idle、min-idle),确保该 Bean 在LettuceConnectionFactory初始化之后注册,否则可能绑定失败
命中率和错误率得自己算,INFO stats 是最稳的来源
内置指标不提供 keyspace_hits/keyspace_misses,更没有错误计数器。想看缓存命中率或命令失败次数,必须直连 Redis 执行 INFO stats:
- 用
redisTemplate.getRequiredConnectionFactory().getConnection().info("stats")获取Properties,取keyspace_hits和keyspace_misses字段 - 分母为 0 时需保护,命中率 =
hits / (hits + misses),Prometheus 中建议用rate()计算窗口值,避免累积值误导 - 错误指标如
total_commands_processed、rejected_connections同样来自INFO stats,别指望/actuator/caches端点——它只返回缓存名列表,跟运行时状态无关
真正难的不是拿到数字,而是确认这些指标对应的是谁:@Cacheable 走的是 Spring Cache 抽象层,redisTemplate 是直连,两者指标完全隔离。如果业务里混用,监控出来的“命中率”只是个平均幻觉。











