php nacos服务注册与发现

本文介绍如何在 Laravel 项目中使用 Alibaba Nacos 进行服务注册与发现,包括 Nacos 的安装配置、服务注册流程及实例的增删改查等关键步骤。

本文为joshua317原创文章,转载请注明:转载自joshua317博客 php nacos服务注册与发现 - joshua317的博客

1 扩展安装

安装grpc、protobuf

2 Laravel项目安装

2.1 指定仓库地址

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

2.2 创建测试项目

composer create-project --prefer-dist laravel/laravel test-service "6.*"

2.3 引入依赖包

composer require alibaba/nacos

2.4 启动服务

php artisan serve

也可以指定host和端口号

php artisan serve --host 127.0.0.2 --port 8001

3 nacos服务安装

3.1 选择版本,进行安装

本示例使用nacos-server-2.0.3版本

3.1.1 windows安装

下载地址

https://github.com/alibaba/nacos/releases/download/2.0.3/nacos-server-2.0.3.zip

3.1.2 类Unix平台安装

wget https://github.com/alibaba/nacos/releases/download/2.0.3/nacos-server-2.0.3.tar.gz
tar -xvf nacos-server-$version.tar.gz
cd nacos/bin

3.2 启动服务

3.2.1 类Unix平台启动

启动命令(standalone代表着单机模式运行,非集群模式):

sh startup.sh -m standalone

如果使用的是ubuntu系统,或者运行脚本报错提示[[符号找不到,可尝试如下运行:

bash startup.sh -m standalone

3.2.2 Windows平台启动

启动命令(standalone代表着单机模式运行,非集群模式):

startup.cmd -m standalone

推荐使用下面方式 更改startup.cmd文件,指定单机模式,可以直接双击运。

set MODE="standalone"

3.3 nacos服务访问

http://10.8.0.27:8848/nacos/index.html

初始账号与密码:nacos nacos

4 服务注册、发现

4.1 实例注册

curl -X POST 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=test-service&ip=127.0.0.1&port=8081'

通过App\Console\Commands\NacosRegisterInstance.php文件进行注册

<?php

namespace App\Console\Commands;

use alibaba\nacos\NacosConfig;
use alibaba\nacos\Naming;
use Illuminate\Console\Command;

class NacosRegisterInstance extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'nacos:register:instance';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'nacos:register:instance';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            NacosConfig::setHost("http://127.0.0.1:8848/"); // 配置中心地址
            $naming = Naming::init(
                "test-service",
                "127.0.0.1",
                "8081",
                "",
                "",
                true
            );

            $naming->register();
        } catch (\Exception $exception) {

        }
    }
}

PHP

Copy

通过php artisan命令执行

php artisan nacos:register:instance

4.2 实例发现

curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/instance/list?serviceName=test-service'

通过App\Console\Commands\NacosGetInstance.php文件进行实例发现

<?phpnamespace App\Console\Commands;use alibaba\nacos\NacosConfig;use alibaba\nacos\Naming;use alibaba\nacos\NamingClient;use Illuminate\Console\Command;class NacosGetInstance extends Command{    /**     * The name and signature of the console command.     *     * @var string     */    protected $signature = 'nacos:get:instance';    /**     * The console command description.     *     * @var string     */    protected $description = 'nacos:get:instance';    /**     * Create a new command instance.     *     * @return void     */    public function __construct()    {        parent::__construct();    }    /**     * Execute the console command.     *     * @return mixed     */    public function handle()    {        try {            NacosConfig::setHost("http://127.0.0.1:8848/"); // 配置中心地址            $naming = Naming::init(                "test-service",                "",                "",                "",                "",                true            );            $instances = $naming->listInstances(true);            if ($instances->getHosts()) {                $hosts = [];                foreach ($instances->getHosts() as $v) {                    $hosts[] = $v->getIp() . ":" . $v->getPort();                }                var_dump($hosts);            } else {                throw  new \Exception("未发现实例");            }        } catch (\Exception $exception) {        }    }}

PHP

Copy

通过php artisan命令执行

php artisan nacos:get:instance

4.3 注销实例

curl -X DELETE 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=test-service&ip=127.0.0.1&port=8081'

通过App\Console\Commands\NacosDeleteInstance.php文件进行实例发现

<?phpnamespace App\Console\Commands;use alibaba\nacos\NacosConfig;use alibaba\nacos\Naming;use alibaba\nacos\NamingClient;use alibaba\nacos\NamingConfig;use Illuminate\Console\Command;class NacosDeleteInstance extends Command{    /**     * The name and signature of the console command.     *     * @var string     */    protected $signature = 'nacos:delete:instance';    /**     * The console command description.     *     * @var string     */    protected $description = 'nacos:delete:instance';    /**     * Create a new command instance.     *     * @return void     */    public function __construct()    {        parent::__construct();    }    /**     * Execute the console command.     *     * @return mixed     */    public function handle()    {        try {            NacosConfig::setHost("http://127.0.0.1:8848/"); // 配置中心地址            $naming = Naming::init(                "test-service",                "127.0.0.1",                "8081",                "",                "",                true            );            $response = $naming->delete();        } catch (\Exception $exception) {        }    }}

PHP

Copy

4.3 修改实例

curl -X PUT '127.0.0.1:8848/nacos/v1/ns/instance?serviceName=test-service&ip=127.0.0.1&port=8081&clusterName=TEST1&weight=8&metadata={}'

通过App\Console\Commands\NacosUpdateInstance.php文件进行实例发现

<?phpnamespace App\Console\Commands;use alibaba\nacos\NacosConfig;use alibaba\nacos\Naming;use alibaba\nacos\NamingClient;use alibaba\nacos\NamingConfig;use Illuminate\Console\Command;class NacosUpdateInstance extends Command{    /**     * The name and signature of the console command.     *     * @var string     */    protected $signature = 'nacos:update:instance';    /**     * The console command description.     *     * @var string     */    protected $description = 'nacos:update:instance';    /**     * Create a new command instance.     *     * @return void     */    public function __construct()    {        parent::__construct();    }    /**     * Execute the console command.     *     * @return mixed     */    public function handle()    {        try {            NacosConfig::setHost("http://127.0.0.1:8848/"); // 配置中心地址            $naming = Naming::init(                "test-service",                "127.0.0.1",                "8081",                "",                "0",                true            );            $naming->update();        } catch (\Exception $exception) {        }    }}

PHP

Copy

5 关闭服务器

5.1 Linux/Unix/Mac

sh shutdown.sh

5.2 Windows

shutdown.cmd

或者双击shutdown.cmd运行文件。

本文为joshua317原创文章,转载请注明:转载自joshua317博客 php nacos服务注册与发现 - joshua317的博客

对于使用 Swoole 和 Nacos 注册服务的问题,你可以按照以下步骤进行操作: 1. 首先,确保你已经安装并配置了 Swoole 扩展和 Nacos SDK。 2. 在代码中引入 Swoole 和 Nacos 相关的命名空间: ```php use Swoole\Coroutine; use Swoole\Coroutine\Http\Client; use Swoole\Coroutine\System; use Swoole\Http\Server; use Swoole\Http\Request; use Swoole\Http\Response; use Swoole\Timer; use Swoole\Runtime; use Swoole\Table; use Nacos\NacosClient; ``` 3. 初始化 Nacos 客户端,并设置相关的配置信息: ```php $config = [ 'host' => '127.0.0.1', // Nacos 服务器地址 'port' => 8848, // Nacos 服务器端口号 'namespace' => 'dev', // Nacos 命名空间 'username' => '', // Nacos 登录用户名(如果启用了登录认证) 'password' => '', // Nacos 登录密码(如果启用了登录认证) ]; $nacosClient = new NacosClient($config); ``` 4. 注册服务Nacos: ```php $serviceName = 'YourServiceName'; // 服务名称 $ip = '127.0.0.1'; // 服务 IP 地址 $port = 8080; // 服务端口号 $instance = [ 'ip' => $ip, 'port' => $port, 'weight' => 1, // 服务权重 'healthy' => true, // 是否健康 'enabled' => true, // 是否启用 ]; $nacosClient->registerInstance($serviceName, $instance); ``` 5. 可选步骤:你可以通过定时器来定期发送心跳,以保持服务的在线状态: ```php $interval = 30000; // 心跳间隔时间(单位:毫秒) Timer::tick($interval, function () use ($nacosClient, $serviceName, $instance) { $nacosClient->updateInstance($serviceName, $instance); }); ``` 6. 当你的服务不再需要注册时,可以取消注册: ```php $nacosClient->deregisterInstance($serviceName, $instance); ``` 以上就是使用 Swoole 和 Nacos 注册服务的基本步骤。你可以根据自己的需求进行相应的调整和扩展。希望对你有帮助!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值