PHP code example of ssh / nacos-sdk-php
1. Go to this page and download the library: Download ssh/nacos-sdk-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/ */
ssh / nacos-sdk-php example snippets
use Nacos\Nacos;
$nacos = new Nacos(
string $serverUrl = 'http://localhost:8848', // Nacos 服务器地址
string $namespaceId = 'public', // 命名空间 ID
string $accessKey = '', // AK/SK 认证的 AccessKey
string $secretKey = '', // AK/SK 认证的 SecretKey
?LoggerInterface $logger = null, // 日志接口(PSR-3)
string $username = '', // 用户名密码认证的用户名
string $password = '', // 用户名密码认证的密码
);
$nacos = new Nacos(
'http://localhost:8848', // serverUrl
'public', // namespaceId
'', // accessKey(不使用 AK/SK 时留空)
'', // secretKey
null, // logger
'nacos', // username
'nacos' // password
);
$nacos = new Nacos(
'http://localhost:8848', // serverUrl
'dev-namespace', // namespaceId
'your-access-key', // accessKey
'your-secret-key', // secretKey
null, // logger
'', // username
'' // password
);
$nacos = new Nacos(
'http://localhost:8848',
'dev-namespace', // 非 public 的命名空间
'', '',
null,
'nacos', 'nacos'
);
// 发布配置
bool $nacos->config()->publishConfig(
string $dataId, // 配置 ID
string $group = 'DEFAULT_GROUP', // 分组
string $content, // 配置内容
string $type = 'text' // 配置类型:text / json / yaml / properties / xml / html
);
// 获取配置(返回原始字符串,不会误解析 JSON 内容)
string $nacos->config()->getConfig(
string $dataId,
string $group = 'DEFAULT_GROUP'
);
// 删除配置
bool $nacos->config()->deleteConfig(
string $dataId,
string $group = 'DEFAULT_GROUP'
);
// 监听配置变更(长轮询)
$nacos->config()->listenConfig(
string $dataId, // 配置 ID
string $group, // 分组
callable $callback, // 变更回调函数
int $timeout = 30 // 长轮询超时(秒)
);
// 发布 properties 配置
$nacos->config()->publishConfig('app.properties', 'DEFAULT_GROUP', 'host=127.0.0.1\nport=8080', 'properties');
// 发布 JSON 配置
$nacos->config()->publishConfig('app.json', 'DEFAULT_GROUP', '{"db":"mysql"}', 'json');
// 发布 YAML 配置
$nacos->config()->publishConfig('app.yml', 'DEFAULT_GROUP', 'server:\n port: 8080', 'yaml');
// 获取配置
$content = $nacos->config()->getConfig('app.json', 'DEFAULT_GROUP');
// 返回: '{"db":"mysql"}'(字符串,不会被解析为数组)
// 监听配置变更
$nacos->config()->listenConfig('app.yml', 'DEFAULT_GROUP', function ($data) {
echo "配置已变更: " . json_encode($data);
}, 30);
// 注册服务实例
bool $nacos->discovery()->registerInstance(
string $serviceName, // 服务名
string $ip, // 实例 IP
int $port, // 实例端口
string $group = 'DEFAULT_GROUP', // 分组名
array $metadata = [], // 元数据(键值对)
int $weight = 1, // 权重
bool $ephemeral = true // true=临时实例 false=持久化实例
);
// 注销服务实例
bool $nacos->discovery()->deregisterInstance(
string $serviceName,
string $ip,
int $port,
string $group = 'DEFAULT_GROUP',
bool $ephemeral = true
);
// 获取所有实例
array $nacos->discovery()->getAllInstances(
string $serviceName,
string $group = 'DEFAULT_GROUP',
bool $healthyOnly = true
);
// 选择一个健康实例
?array $nacos->discovery()->selectOneHealthyInstance(
string $serviceName,
string $group = 'DEFAULT_GROUP'
);
// 发送心跳(临时实例保活)
bool $nacos->discovery()->sendHeartbeat(
string $serviceName,
string $ip,
int $port,
string $group = 'DEFAULT_GROUP'
);
// 注册临时实例(推荐)
$nacos->discovery()->registerInstance(
'user-service', '127.0.0.1', 8080,
'DEFAULT_GROUP', ['version' => '1.0.0'], 10, true
);
// 注册持久化实例
$nacos->discovery()->registerInstance(
'user-service', '127.0.0.1', 8081,
'DEFAULT_GROUP', [], 5, false
);
// 注销实例
$nacos->discovery()->deregisterInstance('user-service', '127.0.0.1', 8080, 'DEFAULT_GROUP', true);
// 获取所有实例(含不健康)
$instances = $nacos->discovery()->getAllInstances('user-service', 'DEFAULT_GROUP', false);
// $instances['hosts'] 为实例数组
// 选择一个健康实例(随机负载均衡)
$instance = $nacos->discovery()->selectOneHealthyInstance('user-service');
// $instance['ip'], $instance['port'], $instance['metadata']
// 发送心跳
$nacos->discovery()->sendHeartbeat('user-service', '127.0.0.1', 8080);
// GET 请求
array $nacos->invoker()->get(
string $serviceName,
string $path, // 接口路径
array $params = [], // 查询参数
string $group = 'DEFAULT_GROUP',
int $retryCount = 3 // 重试次数
);
// POST 请求
array $nacos->invoker()->post(
string $serviceName,
string $path,
array $data = [], // 请求体(JSON)
string $group = 'DEFAULT_GROUP',
int $retryCount = 3
);
// 通用请求
array $nacos->invoker()->request(
string $method, // HTTP 方法:GET/POST/PUT/DELETE/PATCH
string $serviceName,
string $path,
array $data = [],
string $group = 'DEFAULT_GROUP',
int $retryCount = 3
);
// 获取健康实例(30 秒缓存)
?array $nacos->invoker()->getHealthyInstance(
string $serviceName,
string $group = 'DEFAULT_GROUP'
);
// 构建服务 URL
string $nacos->invoker()->buildUrl(
array|Instance $instance, // 实例信息
string $path = '/' // 接口路径
);
// 清除缓存
$nacos->invoker()->clearCache(?string $serviceName = null, string $group = 'DEFAULT_GROUP');
// GET 调用
$result = $nacos->invoker()->get('user-service', '/api/users', ['page' => 1]);
// POST 调用
$result = $nacos->invoker()->post('user-service', '/api/users', ['name' => 'test']);
// 获取健康实例
$instance = $nacos->invoker()->getHealthyInstance('user-service');
// 构建服务 URL(不发送请求)
$url = $nacos->invoker()->buildUrl($instance, '/api/users');
// http://127.0.0.1:8080/api/users
// 清除缓存
$nacos->invoker()->clearCache('user-service'); // 指定服务
$nacos->invoker()->clearCache(); // 所有服务
[
'success' => true,
'status_code' => 200,
'data' => [...], // JSON 解码后的数据
'raw' => '...', // 原始响应体
]
// 创建 Feign 客户端(自动缓存,同服务名+分组复用实例)
FeignClient $nacos->feign(
string $serviceName,
string $groupName = 'DEFAULT_GROUP'
);
// Feign 客户端方法
array $feign->get(string $path, array $params = [], int $retryCount = 3);
array $feign->post(string $path, array $data = [], int $retryCount = 3);
array $feign->put(string $path, array $data = [], int $retryCount = 3);
array $feign->delete(string $path, array $params = [], int $retryCount = 3);
array $feign->request(string $method, string $path, array $data = [], int $retryCount = 3);
// 创建 Feign 客户端
$userClient = $nacos->feign('user-service');
$orderClient = $nacos->feign('order-service', 'PROD_GROUP');
// 声明式调用
$users = $userClient->get('/api/users', ['page' => 1]);
$result = $userClient->post('/api/users', ['name' => 'test']);
$result = $userClient->put('/api/users/1', ['name' => 'updated']);
$result = $userClient->delete('/api/users/1');
// 自定义重试次数
$result = $userClient->get('/api/users', [], 5);
// 同时使用多个 Feign 客户端
$productClient = $nacos->feign('product-service');
$products = $productClient->get('/api/products');
use Nacos\Model\Instance;
use Nacos\Model\Config;
use Nacos\Model\Service;
// ── Instance 模型 ──
// 从 Nacos 响应数组创建
$instance = Instance::fromArray([
'serviceName' => 'my-service',
'ip' => '192.168.1.1',
'port' => 8080,
'metadata' => ['secure' => 'true'],
]);
// 直接构造
$instance = new Instance(
string $serviceName,
string $ip,
int $port,
string $groupName = 'DEFAULT_GROUP',
array $metadata = [],
int $weight = 1,
bool $ephemeral = true,
string $namespaceId = 'public'
);
// 常用方法
$instance->isSecure(); // bool — metadata 中 secure=true 时返回 true
$instance->buildUrl('/api/test'); // string — 自动根据 secure 选择 http/https
$instance->toRequestParams(); // array — 转换为 API 请求参数
$instance->toArray(); // array — 序列化为数组
// ── Config 模型 ──
// 从 Nacos 响应数组创建
$config = Config::fromArray([
'dataId' => 'app.yml',
'group' => 'PROD_GROUP',
'content' => 'key: value',
'type' => 'yaml',
]);
// 直接构造
$config = new Config(
string $dataId,
string $group = 'DEFAULT_GROUP',
string $content = '',
string $type = 'text'
);
// 常用方法
$config->setContent('new content'); // 自动更新 md5
$config->getMd5(); // string — 内容的 MD5 哈希
$config->parseContentAsArray(); // ?array — JSON 内容自动解析为数组
$config->toRequestParams(); // array — 转换为 API 请求参数
$config->toArray(); // array — 序列化为数组
// ── Service 模型 ──
$service = Service::fromArray([
'serviceName' => 'my-svc',
'groupName' => 'TEST_GROUP',
'protectThreshold' => 0.5,
]);
$service->getServiceName(); // string
$service->getGroupName(); // string
$service->getProtectThreshold(); // float
$service->toArray(); // array
use Nacos\Webman\NacosService;
// 实时获取配置
$content = NacosService::getConfig('app.json');
// 从本地缓存读取配置(更快,由 NacosProcess 同步)
$dbConfig = NacosService::getConfigFromCache('database');
// 服务发现
$instance = NacosService::getHealthyInstance('user-service');
// Feign 调用
$result = NacosService::get('user-service', '/api/users', ['page' => 1]);
$result = NacosService::post('user-service', '/api/users', ['name' => 'test']);
return [
'' => [
\Nacos\Webman\NacosReadyMiddleware::class,
],
];
bash
composer bash
composer bash
php -r "