PHP code example of xiaosongshu / nacos
1. Go to this page and download the library: Download xiaosongshu/nacos 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/ */
xiaosongshu / nacos example snippets
aId = 'CalculatorService';
$group = 'api';
$serviceName = 'father';
$namespace = 'public';
$client = new \Xiaosongshu\Nacos\Client('http://127.0.0.1:8848','nacos','nacos');
/** 发布配置 */
$client->publishConfig($dataId, $group, json_encode(['name' => 'fool', 'bar' => 'ha']));
/** 创建实例 */
$client->createInstance($serviceName, "192.168.4.110", '9506', $namespace, ['name' => 'tom', 'age' => 15], 50, 1, true)
return [
/** 连接服务器的基本配置 */
'server' => [
'host' => 'http://127.0.0.1:8848',
'username' => 'nacos',
'password' => 'nacos',
'heartbeat_interval' => 5, // 心跳间隔(秒,默认5秒)
],
/** 服务提供者实例的配置 */
'instance' => [
'ip' => '127.0.0.1',
'port' => '8000',
'weight' => 99, // 初始权重(降级时会动态调整)
'timeout_threshold' => 1000, // 超时阈值(毫秒,超过此时间视为超时,用于计算超时率)
],
/** 健康检查与熔断降级配置 */
'health' => [
'stat_window_size' => 10, // 统计窗口大小(最近100个请求用于计算超时率/错误率)
'adjust_cool_down' => 10, // 调整冷却时间(秒,避免频繁调整,默认30秒)
],
/** 需要监听的配置 作为配置,你可能需要尽可能将配置合并到比较少的文件,一个项目一个配置文件最多两个配置文件就足够了。 */
'config' => [
'app' => [
# 是否开启监听
'enable' => true,
# 是否将本节点配置发布到服务器,建议关闭。若开启发布,假设某一个最后启动的节点的配置是错误的,那么客户端将配置发布到服务器上后,导致所有节点的配置都是错误的。
# 只有当你确认你的配置绝对正确之后,才可以开启发布到服务端,发布完成后关闭发布功能。当然,建议你使用服务端后台发布配置,客户端只负责拉取配置。
'publish'=>false,
'dataId' => 'default',
'group' => 'default',
# 需要配监听的配置文件
'file' => __DIR__ . '/application.yaml',
# 监听到配置发生变化的回调
'callback' => function ($content) {
// todo 根据你的应用场景,将配置刷新到内存,或者重启应用,此处仅做示例演示将配置写入文件
file_put_contents(__DIR__ . "/application.yaml", $content);
}
],
],
/** 需要注册的服务 */
'service' => [
// 服务标识:demo
'demo' => [
'enable' => true,
'serviceName' => \Xiaosongshu\Nacos\Samples\DemoService::class,
'namespace' => 'public',
],
// 服务标识:login
'login' => [
'enable' => true,
'serviceName' => \Xiaosongshu\Nacos\Samples\LoginService::class,
'namespace' => 'public',
'contract' => [
'out' => 'logout'
]
]
]
];
e_once __DIR__."/DemoService.php";
配置文件
$config = erver->run();
}catch (\Throwable $exception){
var_dump($exception->getMessage(),$exception->getLine(),$exception->getFile());
}
namespace Xiaosongshu\Nacos\Samples;
/**
* @purpose 示例服务提供者
* @author yanglong
* @time 2025年7月25日12:16:19
*/
class DemoService
{
/**
* 示例方法:添加用户信息
* @param string $name 姓名
* @param int $age 年龄
* @return string
*/
public function add(string $name, int $age): string
{
return "用户添加成功!姓名:{$name},年龄:{$age}(服务端处理时间:" . date('H:i:s') . ")";
}
/**
* 示例方法:获取用户信息
* @param string $name 姓名
* @return array
*/
public function get(string $name): array
{
return [
'name' => $name,
'age' => 25,
'message' => "查询成功(服务端时间:" . date('H:i:s') . ")"
];
}
}
namespace Xiaosongshu\Nacos\Samples;
/**
* @purpose 用户登录服务
* @author yanglong
* @time 2025年7月25日17:32:27
*/
class LoginService
{
/**
* 用户登录接口
* @param string $username 用户名(必填,长度≥3)
* @param string $password 密码(必填,长度≥6)
* @return array 登录结果,包含token
*/
public function login(string $username, string $password): array
{
// 模拟业务逻辑:验证用户名密码
if (strlen($username) < 3) {
return ['success' => false, 'message' => '用户名长度不能少于3位'];
}
if (strlen($password) < 6) {
return ['success' => false, 'message' => '密码长度不能少于6位'];
}
// 模拟生成token
$token = md5($username . time() . 'secret');
return [
'success' => true,
'message' => '登录成功',
'token' => $token,
'expire' => 3600 // token有效期(秒)
];
}
/**
* 退出登录
* @param string $token
* @return array
*/
public function logout(string $token): array{
return [
'success' => true,
'message' => '退出登录成功',
'token' => $token,
];
}
}
// 使用示例
\JsonRpcClient;
// Nacos配置(与服务端一致)
$nacosConfig = [
'host' => 'http://192.168.110.72:8848',
'username' => 'nacos',
'password' => 'nacos'
];
$client = new JsonRpcClient($nacosConfig);
// 调用login服务(仅需传入服务标识和业务参数)
$loginResult = $client->call('login', [
'username' => 'zhangsan',
'password' => '123456'
]);
// 打印结果
if ($loginResult['success']) {
echo "登录成功:\n";
echo "Token:{$loginResult['result']['token']}\n";
echo "有效期:{$loginResult['result']['expire']}秒\n";
echo "调用实例:{$loginResult['instance']}\n";
} else {
echo "登录失败:{$loginResult['error']}\n";
}
// 退出登录 使用契约
$logoutRes = $client->call('login', ['token' => $loginResult['result']['token']], 'out');
if ($logoutRes['success']) {
echo "退出登录成功:\n";
echo "Token:{$logoutRes['result']['token']}\n";
echo "调用实例:{$logoutRes['instance']}\n";
} else {
echo "退出登录失败:{$logoutRes['error']}\n";
}
/** 测试请求超时,是否会触发服务降级 */
for ($i=0;$i<=10;$i++) {
// 3. 调用DemoService的add方法(添加用户)
$addResult = $client->call(
'demo', // 服务标识(对应服务端配置中的serviceKey)
[
'name' => '张三'.$i, // 对应add方法的$name参数
'age' => 20 // 对应add方法的$age参数
],
'add' // 要调用的方法名(DemoService的add方法)
);
// 处理add方法结果
if ($addResult['success']) {
echo "添加用户结果:{$addResult['result']}\n";
echo "调用的服务实例:{$addResult['instance']}\n\n";
} else {
echo "添加用户失败:{$addResult['error']}\n\n";
}
}
// 4. 调用DemoService的get方法(查询用户)
$getResult = $client->call(
'demo', // 服务标识(不变)
[
'name' => '张三' // 对应get方法的$name参数
],
'get' // 要调用的方法名(DemoService的get方法)
);
// 处理get方法结果
if ($getResult['success']) {
echo "查询用户结果:\n";
print_r($getResult['result']); // 打印数组结果
echo "调用的服务实例:{$getResult['instance']}\n";
} else {
echo "查询用户失败:{$getResult['error']}\n";
}
return [
/** 连接服务器的基本配置 */
'server' => [
'host' => 'http://127.0.0.1:8848',
'username' => 'nacos',
'password' => 'nacos',
'heartbeat_interval' => 5, // 心跳间隔(秒,默认5秒)
],
/** 服务提供者实例的配置 */
'instance' => [
'ip' => '127.0.0.1',
'port' => '9562',
'weight' => 100, // 初始权重(降级时会动态调整)
'timeout_threshold' => 1000, // 超时阈值(毫秒,超过此时间视为超时,用于计算超时率)
],
/** 健康检查与熔断降级配置 */
'health' => [
'stat_window_size' => 10, // 统计窗口大小(最近100个请求用于计算超时率/错误率)
'adjust_cool_down' => 10, // 调整冷却时间(秒,避免频繁调整,默认30秒)
],
'config' => [
'app' => [
# 是否开启监听
'enable' => false,
'dataId' => 'default',
'group' => 'default',
'file' => __DIR__ . '/application.yaml',
'callback' => function ($content) {
file_put_contents(__DIR__ . "/application.yaml", $content);
}
],
],
/** 需要注册的服务 */
'service' => [
'wechat' => [
'enable' => true,
'serviceName' => \app\service\WechatService::class,
'namespace' => 'public',
],
]
];
namespace app\service;
/**
* @purpose 服务提供者
* @author yanglong
* @time 2025年8月1日11:00:17
*/
class WechatService
{
/**
* 业务逻辑
* @param string $phone
* @param string $wechat
* @return array
*/
public function handle(string $phone,string $wechat)
{
//todo 这里是你的业务逻辑,请根据实际需求完善
return ['status'=>200,'message'=>'ok'];
}
}
namespace app\command;
use app\service\Token;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use Xiaosongshu\Nacos\Server;
/**
* @purpose 测试微服务
* @author yanglong
* @time 2025年8月1日11:56:06
* @command nohup php think start:nacos >/dev/null 2>&1 &
*/
class NacosServer extends Command
{
protected function configure()
{
// 指令配置
$this->setName('start:nacos');
// 设置参数
}
protected function execute(Input $input, Output $output)
{
// 指令输出
$configFile = $this->getConfigPath(). '/nacos.php';
if (file_exists($configFile)) {
$config = ;
};
$server->run();
}catch (\Throwable $exception){
$this->error(400,$exception->getMessage());
var_dump($exception->getMessage());
}
}
}
/**
* 错误日志
* @param int $code 状态码
* @param string $message 消息
* @return void
*/
public function error(int $code, string $message)
{
$file = Token::getLogPath() . date('Y_m_d')."_nacos_error.log";
$content = "[error]时间:" . date('Y-m-d H:i:s') . " 消费者[0]"." 状态码:{$code} 消息:发生了异常, 详情:" . $message. "\r\n";
file_put_contents($file,$content);
}
/**
* 运行日志
* @param int $code
* @param string $message
* @return void
*/
public function log(int $code, string $message)
{
$file = Token::getLogPath() . date('Y_m_d')."_nacos_info.log";
$content = "[info]时间:" . date('Y-m-d H:i:s') . " 消费者[0]"." 状态码:{$code} 消息:运行日志, 详情:" . $message. "\r\n";
file_put_contents($file,$content);
}
/**
* 获取配置文件路径
* @return string
*/
public function getConfigPath()
{
return dirname(__DIR__,2)."/config";
}
}
iaosongshu\Nacos\JsonRpcClient;
$client = new JsonRpcClient(self::$nacosConfig);
$client->call('wechat',['phone'=>$phone,'wechat'=>$wechat],'handle');
bash
php server.php
bash
php client.php
bash
php think start:nacos
bash
nohup php think start:nacos >/dev/null 2>&1 &