yu Run Software / nacos-php
Nacos PHP客户端,也支持Swoole协程
v1.0.5
2024-07-04 10:24 UTC
Requires
- php: >=7.4
- psr/log: ^1.0|^2.0|^3.0
- yurunsoft/yurun-http: ^4.3|^5.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.8
- phpunit/phpunit: ^9.5
- swoole/ide-helper: ^4.8
Suggests
- monolog/monolog: Support log
This package is auto-updated.
Last update: 2024-09-04 10:51:23 UTC
README
英语 | 中文
Nacos php 客户端 SDK 允许您访问 Nacos 服务,支持服务发现和动态配置。
请求和响应数据都是强类型,且对IDE友好。
完整的测试案例和支持Swoole协程。
要求
支持的PHP版本超过7.4
支持的Swoole版本超过4.4
支持的Nacos版本超过1.x
安装
使用Composer安装SDK:
composer require yurunsoft/nacos-php
快速示例
客户端
use Yurun\Nacos\Client; use Yurun\Nacos\ClientConfig; // The parameters of ClientConfig are all optional, the ones shown below are the default values // You can write only the configuration items you want to modify $config = new ClientConfig([ 'host' => '127.0.0.1', 'port' => 8848, 'prefix' => '/', 'username' => '', 'password' => '', 'timeout' => 60000, // Network request timeout time, in milliseconds 'ssl' => false, // Whether to use ssl(https) requests 'authorizationBearer' => false, // Whether to use the request header Authorization: Bearer {accessToken} to pass Token, older versions of Nacos need to be set to true 'maxConnections' => 16, // Connection pool max connections 'poolWaitTimeout' => 30, // Connection pool wait timeout when get connection, in seconds // Custom configuration processor to convert string configuration values to arbitrary types (e.g. arrays), which can override the default processing 'configParser' => [ // type Name => callback(string value): mixed 'json' => static fn (string $value): array => json_decode($value, true), ], ]); // Instantiating the client, Not required $client = new Client($config); // Enable log, Support PSR-3 $logger = new \Monolog\Logger(); $client = new Client($config, $logger); // Reopening the client, you can execute the first execution in the Swoole worker, process $client->reopen();
提供者
// Get provider from client $auth = $client->auth; $config = $client->config; $namespace = $client->namespace; $instance = $client->instance; $service = $client->service; $operator = $client->operator;
动态配置
获取配置
$value = $client->config->get('dataId', 'group');
获取解析后的配置
支持json、xml、yaml(需要yaml扩展)Nacos >= 1.4
$client->config->set('dataId', 'group', json_encode(['id' => 19260817]), 'json'); $value = $client->config->getParsedConfig('dataId', 'group', '', $type); // output: // array(1) { // ["id"]=> // int(19260817) // } var_dump($value); var_dump($type); // json
设置配置
$client->config->set('dataId', 'group', 'value');
删除配置
$client->config->delete('dataId', 'group', 'value');
监听配置
配置监听器
use Yurun\Nacos\Provider\Config\ConfigListener; use Yurun\Nacos\Provider\Config\Model\ListenerConfig; // Get config listener $listenerConfig = new ListenerConfig([ 'timeout' => 30000, // The config listener long polling timeout, in milliseconds. The result is returned immediately when the value is 0. 'failedWaitTime' => 3000, // Waiting time to retry after failure, in milliseconds 'savePath' => '', // Config save path, default is empty and not saved to file 'fileCacheTime' => 0, // The file cache time, defaulted to 0, is not affected by caching, and this configuration only affects pull operations. ]); $listener = $client->config->getConfigListener($listenerConfig); $dataId = 'dataId'; $groupId = 'groupId'; $tenant = ''; // Add listening item $listener->addListener($dataId, $groupId, $tenant); // Add listening item with callback $listener->addListener($dataId, $groupId, $tenant, function (\ConfigListener $listener, string $dataId, string $group, string $tenant) { // $listener->stop(); }); // Pull configuration for all listeners (not required) // Forced pull, not affected by fileCacheTime $listener->pull(); $listener->pull(true); // Pull, affected by fileCacheTime $listener->pull(false); // Manually perform a poll $listener->polling(); // The timeout in the ListenerConfig is used as the timeout time. $listener->polling(30000); // Specify the timeout period $listener->polling(0); // Return results immediately // Start the polling listener and do not continue with the following statements until you stop $listener->start(); // To get the configuration cache from the listener, you need to call it in another coroutine $value = $listener->get($dataId, $groupId, $tenant, $type); var_dump($type); // Data type // To get the configuration cache (Arrays or objects after parsing) from the listener, you need to call it in another coroutine $value = $listener->getParsed($dataId, $groupId, $tenant, $type); var_dump($type); // Data type
手动监听配置
建议使用配置监听器
use Yurun\Nacos\Provider\Config\Model\ListenerRequest; $md5 = ''; while (true) { $request = new ListenerRequest(); $request->addListener('dataId', 'group', $md5); $items = $client->listen($request); foreach ($items as $item) { if ($item->getChanged()) { $value = $config->get($item->getDataId(), $item->getGroup(), $item->getTenant()); var_dump('newValue:', $value); $md5 = md5($value); } } }
服务发现
注册实例
$client->instance->register('192.168.1.123', 8080, 'Service1'); // Complete Parameters $client->instance->register('192.168.1.123', 8080, 'Service1', $namespaceId = '', $weight = 1, $enabled = true, $healthy = true, $metadata = '', $clusterName = '', $groupName = '', $ephemeral = false);
注销实例
$client->instance->deregister('192.168.1.123', 8080, 'Service1'); // Complete Parameters $client->instance->deregister('192.168.1.123', 8080, 'Service1', $namespaceId = '', $clusterName = '', $groupName = '', $ephemeral = false);
更新实例
$client->instance->update('192.168.1.123', 8080, 'Service1'); // Complete Parameters $client->instance->update('192.168.1.123', 8080, 'Service1', $namespaceId = '', $weight = 1, $enabled = true, $healthy = true, $metadata = '', $clusterName = '', $groupName = '', $ephemeral = false);
心跳
use Yurun\Nacos\Provider\Instance\Model\RsInfo; $beat = new RsInfo(); $beat->setIp('192.168.1.123'); $beat->setPort(8080); $client->instance->beat('Service1', $beat);
获取实例列表
$response = $client->instance->list('Service1'); $response = $client->instance->list('Service1', $groupName = '', $namespaceId = '', $clusters = '', $healthyOnly = false);
获取实例详情
$response = $client->instance->detail('192.168.1.123', 8080, 'Service1'); // Complete Parameters $response = $client->instance->detail('192.168.1.123', 8080, 'Service1', $groupName = '', $namespaceId = '', $clusters = '', $healthyOnly = false, $ephemeral = false);
其他更多功能接口可以通过查看提供者对象的IDE提示和Nacos文档来使用。
文档
您可以从Nacos Open API指南查看开放API文档。
您可以从Nacos网站查看完整文档。