ClientManger.php 1.2 KB
<?php

namespace AukeySwrpc;

use AukeySwrpc\Client;
use AukeySwrpc\Register\Consul;

/**
 * 客户端管理器
 * Class ClientManger
 *
 * @package App\Clients
 * @author pengjch 202435 23:20:30
 */
class ClientManger
{
    /** @var \Hprose\Client */
    private static $clients;

    private function __sleep()
    {
    }

    private function __wakeup()
    {
    }

    private function __construct()
    {
    }

    /**
     * @param $key
     * @return Client
     * @throws \Exception
     * @author pengjch 2024314 12:34:8
     */
    public static function getInstance($key): Client
    {
        if (!isset(self::$clients[$key])) {
            $registerUri = env('SWRPC_REGISTER_URI');
            if ($registerUri) { //从注册中心获取连接地址
                self::$clients[$key] = Client::createBalancer($key, new Consul($registerUri));
            } else { //直连模式
                $conf = explode(':', env($key));
                if (!$conf || count($conf) != 2) {
                    throw new \Exception('.env未配置' . $key);
                }
                self::$clients[$key] = Client::create($key, $conf[0], $conf[1]);
            }
        }

        return self::$clients[$key];
    }
}