Hyperf 中获取 RPC 连接池当前连接数需通过 DI 容器获取对应命名的 ConnectionPool 实例(如 ConnectionPool::class . '::default'),调用 getStats() 方法获取 created、available、used、waiting 等实时统计值;gRPC 等协议使用特定 Pool 类但接口一致;生产环境推荐通过 Metrics 暴露 Prometheus 指标监控。

Hyperf 中获取 RPC 连接池的当前连接数,主要依赖于其底层使用的 ConnectionPool 实例,尤其是针对 gRPC 或 JSON RPC(如通过 `hyperf/rpc-client`) 所配置的连接池。Hyperf 默认使用 `Hyperf\Pool\ConnectionPool` 管理连接,但连接数统计需通过具体 Pool 实例或其监控接口获取。
查看配置的 RPC 连接池名称和类
Hyperf 的 RPC 客户端连接池通常在 config/autoload/rpc_client.php 中定义,例如:
'pool' => [
'min_connections' => 1,
'max_connections' => 32,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
],
该配置最终会绑定到一个 Hyperf\Pool\ConnectionPool 实例,并以服务名(如 default)注册进 DI 容器。关键是要拿到对应 Pool 的实例。
通过 DI 容器获取 Pool 实例并读取状态
在任意可访问容器的地方(如 Command、Controller、Service),可通过以下方式获取连接池并检查连接数:
- 使用
$container->get(ConnectionPool::class)仅适用于默认单例池;更准确的是按命名获取,例如:$pool = $container->get(ConnectionPool::class . '::default'); - 调用
$pool->getStats()方法,返回数组包含:created(已创建连接数)、available(空闲连接数)、used(正在使用的连接数)、waiting(等待获取连接的协程数)等 - 注意:不同 RPC 协议可能使用不同 Pool 类型。例如 gRPC 使用
Hyperf\Grpc\Pool\GrpcConnectionPool,它也实现了getStats(),行为一致
在命令行中快速验证连接池状态
可新建一个自定义 Command,注入并打印 Pool 统计信息:
public function handle(ContainerInterface $container)
{
$pool = $container->get(ConnectionPool::class . '::default');
$stats = $pool->getStats();
$this->line('Created: ' . $stats['created']);
$this->line('Available: ' . $stats['available']);
$this->line('Used: ' . $stats['used']);
$this->line('Waiting: ' . $stats['waiting']);
}
执行 php bin/hyperf.php your:command 即可看到实时连接数。
通过 Metrics 暴露连接池指标(生产推荐)
若已启用 hyperf/metric 和 Prometheus 支持,Hyperf 会自动采集连接池指标:
- 指标名类似
hyperf_pool_connections_total{pool="default",state="created"} - 需确保
config/autoload/metric.php中启用了pool采集器 - Prometheus endpoint(如
/metrics)可直接查到各状态连接数,适合监控告警


















