jhlater/nacos-php

This package is abandoned and no longer maintained. The author suggests using the jhlater/nacos-php package instead.

Nacos PHP client, which also supports Swoole Coroutine

1.0.2 2024-04-19 00:55 UTC

This package is auto-updated.

Last update: 2024-04-19 00:57:37 UTC


README

Latest Version GitHub Workflow Status (branch) Php Version Swoole Version License

English | 中文

Nacos php sdk for Go client allows you to access Nacos service, it supports service discovery and dynamic configuration.

Request and response data are all strongly typed and IDE friendly.

Complete test cases and support for Swoole Coroutine.

Requirements

Supported PHP version over 7.4

Supported Swoole version over 4.4

Supported Nacos version over 1.x

Installation

Use Composer to install SDK:

composer require yurunsoft/nacos-php

Quick Examples

Client

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();

Providers

// Get provider from client

$auth = $client->auth;
$config = $client->config;
$namespace = $client->namespace;
$instance = $client->instance;
$service = $client->service;
$operator = $client->operator;

Dynamic configuration

Get config

$value = $client->config->get('dataId', 'group');

Get parsed config

Support json, xml, yaml (Required: yaml extension) 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

Set config

$client->config->set('dataId', 'group', 'value');

Delete config

$client->config->delete('dataId', 'group', 'value');

Listen config

Config listener

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
Manual Listening Configuration

Recommend using the config listener

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);
        }
    }
}

Service Discovery

Register instance

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

Deregister instance

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

Update instance

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

Heartbeat

use Yurun\Nacos\Provider\Instance\Model\RsInfo;

$beat = new RsInfo();
$beat->setIp('192.168.1.123');
$beat->setPort(8080);
$client->instance->beat('Service1', $beat);

Get instance list

$response = $client->instance->list('Service1');
$response = $client->instance->list('Service1', $groupName = '', $namespaceId = '', $clusters = '', $healthyOnly = false);

Get instance detail

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

Other more functional interfaces can be used by referring to the provider object's IDE tips and Nacos documentation.

Documentation

You can view the open-api documentation from the Nacos Open API Guide.

You can view the full documentation from the Nacos website.