天天看点

thinkphp 6.0 将服务注册到nacos同时 调用nacos的服务

作者:花刀太岁

在 ThinkPHP 6.0 中将服务注册到 Nacos 并调用 Nacos 的服务,你需要使用 Nacos 的 PHP 客户端库来实现与 Nacos 的交互。以下是一个简单的示例代码,演示了如何在 ThinkPHP 6.0 中注册服务到 Nacos,并调用 Nacos 的服务:

  1. 首先,安装 Nacos PHP 客户端库,你可以使用 Composer 进行安装:
composer require php-nacos/php-nacos           
  1. 创建一个 app/service/NacosService.php 文件,用于封装与 Nacos 交互的逻辑:
<?php

namespace app\service;

use Nacos\Exceptions\NacosException;
use Nacos\Nacos;
use think\facade\Config;

class NacosService
{
    protected $nacos;

    public function __construct()
    {
        $config = Config::get('nacos');

        $this->nacos = new Nacos($config['host'], $config['port'], $config['namespace']);

        // 可选配置项
        $this->nacos->setUsername($config['username']);
        $this->nacos->setPassword($config['password']);
    }

    /**
     * 注册服务到 Nacos
     *
     * @param string $serviceName
     * @param string $ip
     * @param int $port
     * @param string $namespace
     * @throws NacosException
     */
    public function registerService(string $serviceName, string $ip, int $port, string $namespace = '')
    {
        $this->nacos->registerService($serviceName, $ip, $port, $namespace);
    }

    /**
     * 从 Nacos 调用服务
     *
     * @param string $serviceName
     * @param string $namespace
     * @return mixed
     * @throws NacosException
     */
    public function callService(string $serviceName, string $namespace = '')
    {
        return $this->nacos->selectService($serviceName, $namespace);
    }
}
           
  1. 在 config 目录下创建一个 nacos.php 配置文件,用于存放 Nacos 的相关配置信息:
return [
    'host' => '127.0.0.1',  // Nacos 服务端地址
    'port' => 8848,         // Nacos 服务端端口
    'namespace' => '',      // Nacos 命名空间,可选
    'username' => '',       // Nacos 认证用户名,可选
    'password' => '',       // Nacos 认证密码,可选
];           
  1. 在控制器中使用 NacosService 来注册服务到 Nacos 和调用 Nacos 的服务:
namespace app\controller;

use app\service\NacosService;
use think\facade\Request;

class ExampleController
{
    public function registerService(NacosService $nacosService)
    {
        $serviceName = 'your-service-name';
        $ip = Request::ip();
        $port = 8000;

        $nacosService->registerService($serviceName, $ip, $port);

        return 'Service registered to Nacos successfully.';
    }

    public function callService(NacosService $nacosService)
    {
        $serviceName = 'service-to-call';

        $result = $nacosService->callService($serviceName);

        return $result;
    }
}           

确保你在路由中定义了相应的路由规则,例如:

use think\facade\Route;

Route::post('registerService', 'ExampleController@registerService');
Route::get('callService', 'ExampleController@callService');           

上述代码演示了如何在 ThinkPHP 6.0 中注册服务到 Nacos 和调用 Nacos 的服务。你可以根据自己的实际情况进行调整和扩展。记得根据需要修改 your-service-name 和 service-to-call,以及其他相关配置信息。