PHP code example of erikwang2013 / consul-php

1. Go to this page and download the library: Download erikwang2013/consul-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

erikwang2013 / consul-php example snippets


// 所有框架都使用相同 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');

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',
]);

$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');

$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();  // 在另一进程/协程中调用以停止监听

$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');

$health = $client->health;

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

$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 = $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(); // 阻塞获取结果

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

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

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

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

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

// 热更新 — ConsulWatchProcess 自动启动

// 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', ...);
    }
}

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

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

class ConsulService extends BaseConsulService
{
}

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

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

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

$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,可选
);

try {
    $client->kv->get('key');
} catch (ClientException $e) {
    // 网络问题
} catch (NotFoundException $e) {
    // 资源不存在
} catch (ConsulException $e) {
    // 其他 Consul 错误
}
bash
# 核心包
composer �一)
composer 
bash
php artisan vendor:publish --tag=consul-config
bash
php bin/hyperf.php vendor:publish consul