PHPackages                             erikwang2013/consul-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. erikwang2013/consul-php

ActiveLibrary[HTTP &amp; Networking](/categories/http)

erikwang2013/consul-php
=======================

PHP Consul client with full API v1 coverage, service discovery, and config center. Auto-integrates with Laravel, Hyperf, webman, and ThinkPHP.

v3.0.2(2mo ago)1160↓88.9%MITPHPPHP &gt;=8.0CI passing

Since May 14Pushed 2mo agoCompare

[ Source](https://github.com/erikwang2013/consul-php)[ Packagist](https://packagist.org/packages/erikwang2013/consul-php)[ RSS](/packages/erikwang2013-consul-php/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (4)Dependencies (13)Versions (5)Used By (0)

erikwang2013/consul-php
=======================

[](#erikwang2013consul-php)

PHP Consul 客户端，完整覆盖 Consul HTTP API v1，重点支持服务注册发现与配置中心。核心包零框架依赖，内置 Laravel / Hyperf / webman / ThinkPHP 适配，一个 composer require 即可在任何框架下使用。

PHP 8.0+ · PSR-18/PSR-3/PSR-14/PSR-16 · 零框架依赖

---

文档导航
----

[](#文档导航)

文档链接**文档总目录**[docs/README.md](docs/README.md)**Laravel 集成**见下方 [Laravel](#laravel)**Hyperf 集成**见下方 [Hyperf](#hyperf)**webman 集成**见下方 [webman](#webman)**ThinkPHP 集成**见下方 [ThinkPHP](#thinkphp)**设计文档**[docs/superpowers/specs/2026-05-14-consul-php-design.md](docs/superpowers/specs/2026-05-14-consul-php-design.md)---

框架集成一览
------

[](#框架集成一览)

LaravelHyperfwebmanThinkPHP**扩展包**内置内置内置内置**注入方式**自动发现 + `ServiceProvider`自动发现 + `ConfigProvider`手动 `new` / 插件手动 `bind` 到容器**便捷访问**`Consul` Facade`#[Inject]` 注解—`app('consul')` 助手**配置位置**`config/consul.php``config/autoload/consul.php``config/plugin/erikwang2013/consul-php/app.php``config/consul.php`**HTTP 客户端**Guzzle (PSR-18)Swoole 协程客户端Guzzle (PSR-18)Guzzle (PSR-18)**缓存**Laravel Cache (PSR-16)Hyperf Cache (PSR-16)自行注入自行注入**热更新运行**Artisan 命令`AbstractProcess` 协程`Worker` 进程Timer / Swoole 进程**事件监听**`EventServiceProvider`Hyperf Event—ThinkPHP Listener**文档**[源码](src/Integration/Laravel/)[源码](src/Integration/Hyperf/)[源码](src/Integration/Webman/)[源码](src/Integration/Thinkphp/)### 同一操作，不同写法

[](#同一操作不同写法)

**获取客户端：**

框架写法通用`$client = new ConsulClient(['base_uri' => '...']);`Laravel`$client = app(ConsulClient::class);` 或 `Consul::kv->get(...)`Hyperf`#[Inject] private ConsulClient $consul;`webman`$client = new ConsulClient(['base_uri' => '...']);`ThinkPHP`$client = app('consul');`**服务注册：**

```
// 所有框架都使用相同 API，区别仅在于获取 $client 的方式
$client->serviceRegistry()->register('my-app', '10.0.0.1', 8080, [
    'id'    => 'my-app-1',
    'tags'  => ['v1'],
    'check' => ['ttl' => '30s'],
]);
```

**配置读取：**

```
// 相同的 API，Laravel/Hyperf 自动走缓存
$dbHost = $client->configCenter()->get('app/db_host', 'default');
```

**热更新运行方式：**

框架启动命令 / 方式运行环境Laravel`php artisan consul:watch`独立 Artisan 进程Hyperf`ConsulWatchProcess` (自动启动)Swoole 协程webman在 `onWorkerStart` 中 forkWorker 进程ThinkPHPTimer::setInterval / Swoole Process独立进程---

安装
--

[](#安装)

```
# 核心包
composer require erikwang2013/consul-php

# PSR-18 实现（选其一）
composer require guzzlehttp/guzzle php-http/guzzle7-adapter php-http/discovery
```

### 框架集成

[](#框架集成)

框架适配已内置在核心包中，无需额外安装。安装核心包后，对应框架会自动发现并注册 Consul 服务：

- **Laravel** — 自动发现 `ConsulServiceProvider`，提供 `Consul` Facade 和依赖注入
- **Hyperf** — 自动发现 `ConfigProvider`，提供协程客户端工厂和 `#[Inject]` 注入
- **webman** — 自动发现插件，`composer install` 时自动复制配置文件
- **ThinkPHP** — 在 `app/service` 目录下创建 `ConsulService` 并注册到应用

---

快速开始（通用）
--------

[](#快速开始通用)

```
use Erikwang2013\Consul\Client\ConsulClient;

// 基础用法
$client = new ConsulClient(['base_uri' => 'http://127.0.0.1:8500']);

// 带 ACL Token
$client = new ConsulClient([
    'base_uri' => 'http://127.0.0.1:8500',
    'token'    => 'your-consul-acl-token',
]);
```

Token 会自动通过 `X-Consul-Token` 请求头附加到所有请求中。

### 服务注册

[](#服务注册)

支持 TTL、HTTP、TCP、gRPC 四种健康检查模式。

```
$registry = $client->serviceRegistry();

// TTL 模式 — 应用主动发心跳
$registry->register('user-service', '192.168.1.10', 8080, [
    'id'    => 'user-service-1',
    'tags'  => ['v1', 'primary'],
    'meta'  => ['region' => 'cn-east'],
    'check' => [
        'ttl' => '30s',
        'deregister_critical_service_after' => '120s', // 心跳超时自动注销
    ],
]);

// HTTP 模式 — Consul 定期探测
$registry->register('web', '192.168.1.10', 80, [
    'id'    => 'web-1',
    'check' => [
        'http'     => 'http://192.168.1.10:80/health',
        'interval' => '10s',
        'timeout'  => '3s',
    ],
]);

// TCP 模式
$registry->register('mysql', '192.168.1.10', 3306, [
    'check' => ['tcp' => '192.168.1.10:3306', 'interval' => '10s'],
]);

// gRPC 模式
$registry->register('grpc-svc', '192.168.1.10', 50051, [
    'check' => ['grpc' => '192.168.1.10:50051', 'interval' => '10s'],
]);

// 心跳（TTL 模式）
$registry->heartbeat('user-service-1');

// 下线
$registry->deregister('user-service-1');
```

### 服务发现

[](#服务发现)

内置 RoundRobin（默认）和 Random 两种负载均衡策略。

```
$discovery = $client->serviceDiscovery();

// 全部健康实例
$instances = $discovery->healthyInstances('user-service');
// [
//   ['address' => '10.0.0.1', 'port' => 8080, 'service' => 'user-service', 'id' => 'user-1', 'tags' => ['v1']],
//   ['address' => '10.0.0.2', 'port' => 8080, 'service' => 'user-service', 'id' => 'user-2', 'tags' => ['v1']],
// ]

// 负载均衡选一个
$instance = $discovery->selectInstance('user-service');

// 自定义负载均衡策略
use Erikwang2013\Consul\Service\LoadBalancer\Random;
$discovery = new Discovery($health, loadBalancer: new Random());

// 监听服务实例变更
$discovery->watch('user-service', function (array $instances) {
    // 实例上下线时回调
});

// 停止监听（在另一进程/协程中调用）
$discovery->stop();
```

### 配置中心

[](#配置中心)

```
$config = $client->configCenter();

// 单个键
$dbHost = $config->get('app/db_host', 'localhost');

// 整个命名空间
$all = $config->namespace('app/');
// ['app/db_host' => 'mysql.local', 'app/redis_host' => 'redis.local', ...]

// 写入 / 删除
$config->set('app/cache_ttl', '3600');
$config->delete('app/old_key');

// 热更新
$watcher = $config->watch('app/');
$watcher
    ->setBlockingWait(30)   // 长轮询超时（秒）
    ->setPollInterval(10)   // 降级为轮询的间隔（秒）
    ->onChange(function (array $updated) {
        // 配置变更回调
    });
$watcher->start(); // 阻塞，放入独立进程/协程
// $watcher->stop();  // 在另一进程/协程中调用以停止监听
```

**热更新原理：** 优先 Consul blocking query（`index` 长轮询），网络异常时自动降级为定时轮询，连接恢复后自动切回长轮询。回调 + PSR-14 EventDispatcher 双通道通知。

**缓存策略：** 注入 PSR-16 缓存后，`get()` 和 `namespace()` 自动读写缓存。Watcher 始终读 Consul 实时数据，不走缓存。

### KV 存储

[](#kv-存储)

```
$kv = $client->kv;

$kv->put('key', 'value');
$entry = $kv->get('key');              // null 表示不存在
$all = $kv->all('prefix/');            // 递归列出
$keys = $kv->keys('prefix/');          // 仅键名
$keys = $kv->keys('prefix/', '/');     // 按分隔符层级列出
$kv->delete('key');
```

### 健康检查 API

[](#健康检查-api)

```
$health = $client->health;

$health->service('user-service', ['passing' => true]);  // 仅健康实例
$health->node('node-1');                                 // 节点所有检查
$health->checks('user-service');                          // 服务所有检查
$health->state('critical');                               // 按状态：passing/warning/critical
```

### Session / 分布式锁

[](#session--分布式锁)

```
$session = $client->session;

$sess = $session->create([
    'Name'     => 'lock-session',
    'TTL'      => '30s',
    'Behavior' => 'delete',    // 过期自动删除关联 KV
]);
$sessionId = $sess['ID'];

// 锁住资源
$locked = $client->kv->put('lock/resource', '1', ['acquire' => $sessionId]);

// 续约 / 释放
$session->renew($sessionId);
$session->destroy($sessionId);
```

### ACL

[](#acl)

```
$acl = $client->acl;

// Token
$token = $acl->tokenCreate(['Description' => 'read-only', 'Policies' => [['Name' => 'read-policy']]]);
$acl->tokenRead($token['AccessorID']);
$acl->tokenDelete($token['AccessorID']);

// Policy
$policy = $acl->policyCreate(['Name' => 'my-policy', 'Rules' => 'node "" { policy = "read" }']);

// Role
$role = $acl->roleCreate(['Name' => 'reader', 'Policies' => [['Name' => 'my-policy']]]);

// Login/Logout
$result = $acl->login(['AuthMethod' => 'my-auth', 'BearerToken' => '...']);
$acl->logout();
```

### 异步客户端

[](#异步客户端)

```
use Erikwang2013\Consul\Client\ConsulAsyncClient;

$client = new ConsulAsyncClient(['base_uri' => 'http://127.0.0.1:8500']);

$promise = $client->wrap(fn() => $client->kv->get('key'));

$promise
    ->then(fn($result) => print_r($result))
    ->catch(fn(\Throwable $e) => log_error($e));

$value = $promise->wait(); // 阻塞获取结果
```

**注意：** 异步客户端基于 Promise 模式，适用于需要并发请求的场景。Hyperf 协程环境中默认的 HTTP 客户端即可实现协程级并发。

---

各框架集成指南
-------

[](#各框架集成指南)

### Laravel

[](#laravel)

Laravel 自动发现 `ConsulServiceProvider`，无需手动注册。

```
php artisan vendor:publish --tag=consul-config
```

`.env` 中设置 `CONSUL_BASE_URI`，之后即可通过依赖注入或 Facade 使用。Laravel 扩展自动注入 PSR-18 客户端、PSR-16 缓存、PSR-3 日志和 PSR-14 事件分发器。

```
// 依赖注入
use Erikwang2013\Consul\Client\ConsulClient;
public function show(ConsulClient $consul) { ... }

// Facade
use Consul;
$services = Consul::catalog->services();

// 配置热更新 — Artisan 命令
// php artisan consul:watch
```

### Hyperf

[](#hyperf)

Hyperf 自动发现 `ConfigProvider`，无需手动注册。

```
php bin/hyperf.php vendor:publish consul
```

Hyperf 扩展自动注册 `ConsulClient` 到 DI 容器，HTTP 请求默认使用 Swoole 协程客户端。服务注册建议放在 `MainServerStart` 事件监听中，热更新使用 `AbstractProcess` 在协程中运行。

```
// 注解注入
#[Inject]
private ConsulClient $consul;

// 服务注册 — MainServerStart 事件
$consul->serviceRegistry()->register(...);

// 热更新 — ConsulWatchProcess 自动启动
```

### webman

[](#webman)

webman 自动发现插件，`composer install` 时自动复制配置文件到 `config/plugin/erikwang2013/consul-php/`。由于 webman 是常驻内存架构，服务注册放在 `onWorkerStart` 回调中，全局只需注册一次。

```
// process/ConsulRegister.php
class ConsulRegister {
    public function onWorkerStart(Worker $worker): void {
        $consul = new ConsulClient(['base_uri' => getenv('CONSUL_BASE_URI')]);
        $consul->serviceRegistry()->register('webman-app', ...);
    }
}
```

### ThinkPHP

[](#thinkphp)

ThinkPHP 无自动发现机制，需手动注册 Service。将配置文件复制到 `config/consul.php`，然后在 `app/service` 目录下注册 `ConsulService`：

```
// app/service/ConsulService.php
namespace app\service;

use Erikwang2013\Consul\Integration\Thinkphp\ConsulService as BaseConsulService;

class ConsulService extends BaseConsulService
{
}
```

或在 `app/AppService.php` 中直接绑定：

```
$this->app->bind('consul', fn() => new ConsulClient(config('consul')));

// 使用
$services = app('consul')->catalog->services();

// 助手函数 — app/common.php
function consul() { return app('consul'); }
```

---

自定义 HTTP 客户端
------------

[](#自定义-http-客户端)

```
$client = new ConsulClient(
    config:          ['base_uri' => 'http://consul:8500', 'token' => 'acl-token'],
    httpClient:      $myPsr18Client,        // 必填或自动发现
    requestFactory:  $myRequestFactory,      // 同上
    streamFactory:   $myStreamFactory,       // 同上
    logger:          $myLogger,              // PSR-3，可选
    cache:           $myCache,               // PSR-16，可选
    eventDispatcher: $myEventDispatcher,     // PSR-14，可选
);
```

---

API 模块速查
--------

[](#api-模块速查)

属性类主要方法`$client->kv``Api\Kv``get` `put` `delete` `all` `keys``$client->agent``Api\Agent``members` `self` `registerService` `deregisterService` `checks` `services``$client->catalog``Api\Catalog``register` `deregister` `nodes` `services` `service` `node``$client->health``Api\Health``service` `node` `checks` `state``$client->session``Api\Session``create` `destroy` `renew` `info` `all` `node``$client->acl``Api\Acl``token*` `policy*` `role*` `authMethod*` `login` `logout` `bootstrap``$client->event``Api\Event``fire` `list``$client->status``Api\Status``leader` `peers``$client->coordinate``Api\Coordinate``datacenters` `nodes` `node``$client->operator``Api\Operator``raftConfig` `autopilotConfig` `keyring`（常量：`KEYRING_LIST` `KEYRING_INSTALL` `KEYRING_USE` `KEYRING_REMOVE`）`$client->snapshot``Api\Snapshot``save`（返回原始快照字节，通过 `getRaw()`） `restore`（发送原始字节，通过 `putRaw()`）高层封装：

方法返回说明`$client->serviceRegistry()``Service\Registry`服务注册/心跳/下线`$client->serviceDiscovery()``Service\Discovery`实例列表/负载均衡/变更监听`$client->configCenter()``Config\ConfigCenter`配置读写/缓存/热更新---

异常体系
----

[](#异常体系)

所有异常继承 `ConsulException`（继承 `RuntimeException`）：

```
ConsulException
├── ClientException           HTTP 传输错误（连接失败、DNS、超时等）
├── ServerException           Consul 返回 5xx
└── ConsulRequestException    Consul 返回 4xx
    ├── NotFoundException     404
    └── AccessDeniedException 403

```

```
try {
    $client->kv->get('key');
} catch (ClientException $e) {
    // 网络问题
} catch (NotFoundException $e) {
    // 资源不存在
} catch (ConsulException $e) {
    // 其他 Consul 错误
}
```

---

架构
--

[](#架构)

```
┌─────────────────────────────────────┐
│            ConsulClient              │  ← 统一入口（同步 + 异步）
├─────────────────────────────────────┤
│  Service\Registry │ Config\Config   │  ← 高层封装
│  Service\Discovery│   Center        │
├─────────────────────────────────────┤
│  Api\Agent │ Api\Kv │ Api\Health   │  ← API 模块（11 个）
│  Api\Catalog │ Api\Session │ ...    │
├─────────────────────────────────────┤
│       Transport\Psr18Transport       │  ← PSR-18 传输层
│  get/put/post/delete + getRaw       │     Token 注入 · Header 捕获
│  putRaw + getWithHeaders             │     状态码检查 · JSON 解码
├─────────────────────────────────────┤
│   PSR-18 Client  │  PSR-17 Factory   │  ← 用户注入 / 自动发现
└─────────────────────────────────────┘

```

---

最低要求
----

[](#最低要求)

- PHP 8.0+
- Composer
- PSR-18 HTTP Client 实现
- \[可选\] PSR-16 缓存 — `Discovery::healthyInstances()` / `ConfigCenter::get()` 自动缓存
- \[可选\] PSR-3 Logger — 请求日志
- \[可选\] PSR-14 EventDispatcher — `ConfigChangedEvent` 事件

开源不易，欢迎支持
---------

[](#开源不易欢迎支持)

微信支付宝[![微信](./docs/weixinpay.png "微信")](./docs/weixinpay.png)[![支付宝](./docs/alipay.png "支付宝")](./docs/alipay.png)---

License
-------

[](#license)

MIT

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance86

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

4

Last Release

67d ago

Major Versions

v1.0.1 → v2.0.02026-05-17

v2.0.0 → v3.0.12026-05-18

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/9014941?v=4)[erik](/maintainers/erikwang2013)[@erikwang2013](https://github.com/erikwang2013)

---

Top Contributors

[![erikwang2013](https://avatars.githubusercontent.com/u/9014941?v=4)](https://github.com/erikwang2013 "erikwang2013 (36 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/erikwang2013-consul-php/health.svg)

```
[![Health](https://phpackages.com/badges/erikwang2013-consul-php/health.svg)](https://phpackages.com/packages/erikwang2013-consul-php)
```

###  Alternatives

[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k16](/packages/tempest-framework)[symfony/symfony

The Symfony PHP framework

31.4k87.2M2.2k](/packages/symfony-symfony)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M600](/packages/shopware-core)[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)[cakephp/cakephp

The CakePHP framework

8.8k19.5M1.8k](/packages/cakephp-cakephp)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
