PoolStatus 不支持直接监控 Redis 连接池空闲率,需手动计算 idle/total;可通过 PoolStatusInterface 获取快照数据,结合 Prometheus 定期上报比率,但应重点关注 wait_connections 和 acquire_wait_milliseconds 延迟。

PoolStatus 组件是否支持 Redis 连接池空闲率监控
不支持直接监控 Redis 连接池的“空闲率”。PoolStatus 是 Hyperf 的通用连接池状态收集组件,它只暴露 total_connections、idle_connections、wait_connections 等基础计数,但不自动计算或上报“空闲率 = idle / total”这类衍生指标。你需要自己读取原始值并做除法运算。
如何从 PoolStatus 获取 Redis 连接池的 idle / total 值
Hyperf 会为每个配置的 Redis pool 注册一个 PoolStatus 实例,名称默认为 redis.pool_name(如 redis.default)。可通过 PoolStatusInterface 获取实时数据:
// 在 Command 或 Controller 中
use Hyperf\Pool\PoolStatusInterface;
public function handle(PoolStatusInterface $poolStatus)
{
$status = $poolStatus->get('redis.default');
if ($status) {
$idle = $status['idle_connections'] ?? 0;
$total = $status['total_connections'] ?? 0;
$rate = $total > 0 ? round($idle / $total, 3) : 0;
var_dump("空闲率: {$rate} ({$idle}/{$total})");
}
}
- 必须确保
redis.default在config/autoload/redis.php中已正确定义且启用了pool配置 -
$poolStatus->get()返回的是快照,非持续流式数据;高频调用需注意性能开销 - 若返回
null,常见原因是 pool 名称拼写错误,或该 pool 尚未被初始化(比如从未执行过 Redis 操作)
为什么监控空闲率容易误判连接池健康度
空闲率高 ≠ 健康,低 ≠ 紧张。Redis 连接池行为受业务模式影响极大:
- 短时突发流量会让
idle_connections快速归零,但只要wait_connections不持续增长,就未必是瓶颈 - 长连接 + 低频调用场景下,空闲率常年接近 1.0,但这只是常态,不代表资源浪费
-
max_connections设置过大会拉高分母,导致空闲率虚高;设置过小则易触发等待,但空闲率可能仍不低(因为连接刚被释放又立刻复用)
真正值得关注的是:wait_connections 是否持续 > 0,以及 acquire_wait_milliseconds 的 P95 延迟是否超标。
在 Prometheus 中暴露 Redis 空闲率指标的最小实践
Hyperf 自带 hyperf/metric 和 hyperf/prometheus,可手动注册自定义指标:
// 在 listener 或 provider 中
use Hyperf\Metric\Contract\MetricFactoryInterface;
use Hyperf\Prometheus\Metric\Gauge;
$factory = $container->get(MetricFactoryInterface::class);
$gauge = $factory->makeGauge([
'name' => 'redis_pool_idle_ratio',
'help' => 'Redis connection pool idle ratio',
'labels' => ['pool'],
]);
// 定期采集(例如每 5 秒)
\Swoole\Timer::tick(5000, function () use ($gauge, $poolStatus) {
$status = $poolStatus->get('redis.default');
if ($status && $status['total_connections'] > 0) {
$ratio = $status['idle_connections'] / $status['total_connections'];
$gauge->set($ratio, ['default']);
}
});
- 不要在每次 Redis 调用中计算并上报,避免高频打点拖慢主流程
- 务必加
$status['total_connections'] > 0判断,否则除零会导致 NaN 写入 Prometheus,后续查询异常 - 标签值(如
default)应与配置中的 pool 名一致,方便 Grafana 多实例筛选
空闲率本身是个弱信号,真正要盯住的是 wait 队列长度和获取连接的耗时分布——这两个值才直接反映连接池是否成了瓶颈。


















