Commit c2c0fa44 authored by Liu lu's avatar Liu lu
Browse files

v1.2.13

parent da3c6843
Loading
Loading
Loading
Loading
+104 −0
Original line number Original line Diff line number Diff line
<?php

namespace Meibuyu\Micro\CenterConfig;

use Meibuyu\Micro\CenterConfig\Nacos\NacosDriver;
use Psr\Container\ContainerInterface;

class CenterConfig
{
    private $env = [];

    private $alias = [
        'nacos' => NacosDriver::class,
    ];


    public function load()
    {
        $this->loadEnv();

        //默认nacos驱动
        $dirver = $this->env['CONFIG_CENTER_DRIVER'] ?? 'nacos';

        $isEnable = $this->env['CONFIG_CENTER'] ?? false;
        $isEnable = $isEnable == 'true' ? true : false;
        if($isEnable) {
            $instances = self::getDriverInstance($dirver);
            $instances->fetchConfig($this->env);
        }
    }

    /**
     * Notes: 获取驱动连接实例
     * User: carlos
     * DateTime: 2022/9/9 9:21
     */
    public function getDriverInstance($dirver)
    {
        $className = $this->alias[$dirver];
        return new $className();
    }

    /**
     * Notes: 是否开启配置中心
     * User: carlos
     * DateTime: 2022/9/8 18:27
     * @return bool
     */
    public function isEnable() :bool
    {
        $flag = false;
        $key = 'CONFIG_CENTER';
        if(array_key_exists($key, $this->env) && $this->env[$key]) {
            $flag = true;
        }

        return $flag;
    }

    /**
     * Notes: 加载env文件
     * User: carlos
     * DateTime: 2022/9/8 18:12
     */
    public function loadEnv()
    {
        $envFileName = BASE_PATH.'/.env';
        $handle = fopen($envFileName, 'r');
        if (!$handle) {
            echo '文件打开失败!';
        }
        while (false !== ($char = fgets($handle,1024))) {
            if(strlen(trim($char)) > 0 && $char[0] != '#') {
                try {
                    $res = explode('=', $char);
                    $this->env[$res[0]] = $res[1];
                    $this->setEnv($res[0], $res[1]);
                }catch (\Exception $e) {

                }
            }
        }
        fclose($handle);
    }

    /**
     * @return array
     */
    public function getEnv(): array
    {
        return $this->env;
    }

    /**
     * @param array $env
     */
    public function setEnv($key, $value): void
    {
        $this->env[trim($key)] = trim($value);
    }



}
 No newline at end of file
+26 −0
Original line number Original line Diff line number Diff line
<?php

namespace Meibuyu\Micro\CenterConfig\Driver;

/**
 * 配置中心驱动
 * @author carlos
 */
interface DriverInterface
{
    /**
     * Notes: 拉取配置
     * User: carlos
     * DateTime: 2022/9/9 10:14
     * @return mixed
     */
    public function fetchConfig(array $config);

    /**
     * Notes: 获取连接
     * User: carlos
     * DateTime: 2022/9/9 10:14
     * @return mixed
     */
    public function getClient();
}
 No newline at end of file
+101 −0
Original line number Original line Diff line number Diff line
<?php

namespace Meibuyu\Micro\CenterConfig\Nacos;


class Config
{
    private $baseUri = 'http://127.0.0.1:8848';

    private $guzzleConfig = [
        'headers' => [
            'charset' => 'UTF-8',
        ],
        'http_errors' => false,
    ];

    private $username;

    private $password;

    public function __construct(array $config)
    {
        $baseUri = sprintf('http://%s:%d', $config['NACOS_HOST'] ?? '192.168.1.27', $config['NACOS_PORT'] ?? 8848);
        $this->setBaseUri($baseUri);

        $userName = $config['NACOS_USER'] ?? 'nacos';
        $pass = $config['NACOS_PASS'] ?? 'nacos';

        $this->setUsername($userName);

        $this->setPassword($pass);

    }


    /**
     * @return string
     */
    public function getBaseUri(): string
    {
        return $this->baseUri;
    }

    /**
     * @param string $baseUri
     */
    public function setBaseUri(string $baseUri): void
    {
        $this->baseUri = $baseUri;
    }

    /**
     * @return array
     */
    public function getGuzzleConfig(): array
    {
        return $this->guzzleConfig;
    }

    /**
     * @param array $guzzleConfig
     */
    public function setGuzzleConfig(array $guzzleConfig): void
    {
        $this->guzzleConfig = $guzzleConfig;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username): void
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param mixed $password
     */
    public function setPassword($password): void
    {
        $this->password = $password;
    }


}
 No newline at end of file
+200 −0
Original line number Original line Diff line number Diff line
<?php

namespace Meibuyu\Micro\CenterConfig\Nacos;


use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Meibuyu\Micro\CenterConfig\Driver\DriverInterface;
use Psr\Http\Message\ResponseInterface;

class NacosDriver implements DriverInterface
{
    
    private Config $config;

    private $accessToken;

    private $expireTime;

    /**
     * Notes: 拉取配置文件
     * User: carlos
     * DateTime: 2022/9/9 10:13
     * @param array $config
     */
    public function fetchConfig(array $config)
    {
        $envFileName = BASE_PATH.'/.env';
        //配置nacos配置类
        $this->configure($config);
        if($config['APP_ENV'] == 'dev') {
            $dataId = $config['APP_NAME'];
            $group = $config['APP_ENV'];
            $tenant = $config['APP_ENV'];
        }else{
            $dataId = $config['ENV_DATA_ID'];
            $group = $config['ENV_GROUP'];
            $tenant = $config['ENV_TENANT'];
        }

        $res = $this->get($dataId, $group, $tenant);

        $config['CONFIG_CENTER'] = 'false';
        file_put_contents($envFileName, '');
        foreach ($config as $item=>$value) {
            $content = $item.'='.$value.PHP_EOL;
            file_put_contents($envFileName, $content, FILE_APPEND);
        }
        file_put_contents($envFileName, ''.PHP_EOL, FILE_APPEND);
        file_put_contents($envFileName, $res, FILE_APPEND);
    }

    /**
     * Notes: 获取配置文件
     * User: carlos
     * DateTime: 2022/9/9 13:58
     * @param string $dataId
     * @param string $group
     * @param string|null $tenant
     * @throws \Exception
     */
    public function get(string $dataId, string $group, ?string $tenant = null)
    {
        $res =  $this->request('GET', '/nacos/v1/cs/configs', [
            RequestOptions::QUERY => $this->filter([
                'dataId' => $dataId,
                'group' => $group,
                'tenant' => $tenant,
            ]),
        ]);


        $result = $this->handleResponse(
            $res, 'string'
        );
        return $result;
    }


    protected function filter(array $input): array
    {
        $result = [];
        foreach ($input as $key => $value) {
            if ($value !== null) {
                $result[$key] = $value;
            }
        }

        return $result;
    }


    public function request($method, $uri, array $options = [])
    {
        $token = $this->getAccessToken();
        $token && $options[RequestOptions::QUERY]['accessToken'] = $token;
        return $this->getClient()->request($method, $uri, $options);
    }

    /**
     * Notes: 获取token
     * User: carlos
     * DateTime: 2022/9/9 10:40
     */
    public function getAccessToken()
    {
        $username = $this->config->getUsername();
        $password = $this->config->getPassword();

        if (! $this->isExpired()) {
            return $this->accessToken;
        }

        $result = $this->handleResponse(
            $this->login($username, $password)
        );
        $this->accessToken = $result['accessToken'];
        $this->expireTime = $result['tokenTtl'] + time();

        //return $this->accessToken;
    }

    /**
     * Notes: 查看token是否过期
     * User: carlos
     * DateTime: 2022/9/9 11:01
     * @return bool
     */
    protected function isExpired(): bool
    {
        if (isset($this->accessToken) && $this->expireTime > time() + 60) {
            return false;
        }
        return true;
    }

    /**
     * Notes: nacos登录
     * User: carlos
     * DateTime: 2022/9/9 10:47
     */
    public function login($username, $password) : ResponseInterface
    {
        return $this->getClient()->request('POST', '/nacos/v1/auth/users/login', [
            RequestOptions::QUERY => [
                'username' => $username,
            ],
            RequestOptions::FORM_PARAMS => [
                'password' => $password,
            ],
        ]);
    }

    /**
     * Notes: 解析请求
     * User: carlos
     * DateTime: 2022/9/9 10:47
     * @param ResponseInterface $response
     * @return array
     */
    protected function handleResponse(ResponseInterface $response, $type = 'array')
    {
        $statusCode = $response->getStatusCode();
        $contents = (string) $response->getBody();
//        if ($statusCode !== 200) {
//            throw new \Exception($contents, $statusCode);
//        }
        if($type == 'string') {
            return $contents;
        }else{
            return json_decode($contents, true);
        }
    }



    /**
     * Notes: 配置nacos配置
     * User: carlos
     * DateTime: 2022/9/9 10:32
     * @param array $config
     */
    public function configure(array $config)
    {
        $this->config = new Config($config);
    }

    /**
     * Notes: 获取连接
     * User: carlos
     * DateTime: 2022/9/9 10:14
     */
    public function getClient()
    {
        $config = array_merge($this->config->getGuzzleConfig(), [
            'base_uri' => $this->config->getBaseUri(),
        ]);
        return new Client($config);
    }
}
 No newline at end of file
+8 −0
Original line number Original line Diff line number Diff line
<?php

namespace Meibuyu\Micro\CenterConfig;

class NacosClient
{
    //private 
}
 No newline at end of file