PHP code example of bklab / think-nacos-sdk

1. Go to this page and download the library: Download bklab/think-nacos-sdk 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/ */

    

bklab / think-nacos-sdk example snippets


// 事件定义文件
return [
    // ......
    'listen'    => [
        'AppInit'  => [
            'think\sdk\alibaba\nacos\v2\Nacos', //推荐放到末尾
        ],
    ],
    // ......
];

public function register_nacos()
{
    // 设置用户永远执行
    set_time_limit(0);
    // 设置用户永不超时
    ini_set('max_execution_time', '0');
    // 设置用户中断时继续执行
    ignore_user_abort(true);

    // 获取本机内网IP
    $ip = gethostbyname(gethostname());

    $ip = $this->request->get('ip', $ip);
    $port = $this->request->get('port', 80);

    // 具体配置信息见下方

    return '已将' . $ip . ':' . $port . '注册到Nacos。';
}

$nacos = new \think\sdk\alibaba\nacos\v2\Nacos()
    ->register()    // 注册服务到Nacos
    ;

// 如需动态配置Nacos,请使用此方法获取
$config = new \think\sdk\alibaba\nacos\v2\config\NacosConfig::getInstance();
// 默认通过此方法获取本机内网IP
$config ->setServerIp(gethostbyname(gethostname()));
// 如监听端口非80,且配置文件未填写,则需要手动设置
$config ->setServerPort(8080);

$nacos = new \think\sdk\alibaba\nacos\v2\Nacos()
    ->register()    // 注册服务到Nacos
    ;

\think\Event::listen(
    \think\sdk\alibaba\nacos\v2\event\NacosConfigChangeEvent::class, 
    function ($raw_config){
        dump('nacos config change', $raw_config);
    }
);

$nacos = new \think\sdk\alibaba\nacos\v2\Nacos()
    ->listen()              // 开始监听(每秒查询更改)
    ->cancelListening()     // 当需要停止监听时,调用
    ;