Commit 9c49628b authored by Euan游根明's avatar Euan游根明

perf:优化拉取配置

parent 42f2c9a6
......@@ -15,7 +15,7 @@ if (isset($GLOBALS['_composer_autoload_path'])) {
unset($file);
}
$options = getopt('', array('prepend:'));
$options = getopt('',['base_path:','env.nacos:','env:']);
require NACOS_COMPOSER_INSTALL;
......
......@@ -5,54 +5,56 @@ namespace Galaxy\NacosClient\Nacos;
class Nacos
{
public static array $configs = [];
public static $configs = [];
public static $basePath = '';
public static function run($options)
{
var_dump($options);
die;
self::configure();
$this->info('开始拉取配置文件');
$url = self::$configs['NACOS_URL'] ?? '';
$res = self::configure($options);
if (empty($res)){
return;
}
self::info('开始拉取配置文件');
$url = self::$configs['NACOS_URL'] ?? '';
$group = self::$configs['GROUP'] ?? '';
if (empty($url)){
$this->info('无nacos链接');
self::info('无nacos链接');
return;
}
$appName = env('APP_NAME');
$appEnv = env('APP_ENV');
if ($appName != $group) {
$this->info($group . '应用不匹配');
$modelPath = self::$basePath.'.env';
$envFile = file_get_contents($modelPath);
$configGroup = 'APP_NAME='.$group;
if (!preg_match("/$configGroup/", $envFile)) {
self::info($group . '应用不匹配');
return;
}
$env = '.env';
$modelPath = base_path(). '/' . $env;
$key = $group . '-env-' . $appEnv;
$res = $this->getConfig($key, $group);
$key = $group . '-env-' . self::$configs['APP_ENV'];
$res = self::getConfig($key, $group);
if (empty($res)) {
$log = $key . '配置不存在';
$this->info($log);
self::info($log);
return;
}
try {
$cacheKey = 'fileMd5' . $key;
$md5File = md5($res);
$oldMd5 = Nacos::Nacosget($cacheKey);
$oldMd5 = Nacos::NacosGet($cacheKey);
if (!$oldMd5) {
$this->write($modelPath, $res);
Nacos::Nacosput($cacheKey, $md5File);
self::write($modelPath, $res);
Nacos::NacosPut($cacheKey, $md5File);
$logs = '首次获取配置' . $key;
$this->info($logs);
self::info($logs);
return;
}
$logs = $key . '文件未发生变更' . PHP_EOL;
if ($oldMd5 != $md5File) {
$logs = $key . '文件发生变更,修改配置项' . PHP_EOL;
Nacos::Nacosput($cacheKey, $md5File);
$this->write($modelPath, $res);
Nacos::NacosPut($cacheKey, $md5File);
self::write($modelPath, $res);
}
$this->info($logs);
self::info($logs);
} catch (\Exception $e) {
$this->info('获取配置失败' . $key.': '.$e);
self::info('获取配置失败' . $key.': ');
}
}
......@@ -63,7 +65,7 @@ class Nacos
* @return void
* @throws Exception
*/
public function write($path,$res){
public static function write($path,$res){
$save = file_put_contents($path, $res);
if ($save === false){
throw new Exception('保存配置失败'.$path);
......@@ -77,17 +79,17 @@ class Nacos
* @param $isSync
* @return false|\GuzzleHttp\Promise\PromiseInterface|mixed|string
*/
public function getConfig($dataId, $group = 'DEFAULT_GROUP')
public static function getConfig($dataId, $group = 'DEFAULT_GROUP')
{
try {
return $this->requery($dataId, $group);
return self::requery($dataId, $group);
} catch (\Exception $e) {
$code = $e->getCode();
if ($code == 404) {
return false;
if ($code == 403) {
self::getToken(true);
return self::requery($dataId, $group);
}
$this->getToken(true);
return $this->requery($dataId, $group);
return false;
}
}
......@@ -99,10 +101,10 @@ class Nacos
* @return \GuzzleHttp\Promise\PromiseInterface|mixed|string
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function requery($dataId, $group)
public static function requery($dataId, $group)
{
$url = self::$configs['NACOS_URL'].'/nacos/v2/cs/config?accessToken='.$this->getToken().'&dataId='.$dataId.'&group='.$group;
return $this->getConfigRequest($url);
$url = self::$configs['NACOS_URL'].'/nacos/v2/cs/config?accessToken='.self::getToken().'&dataId='.$dataId.'&group='.$group;
return self::getConfigRequest($url);
}
/**
......@@ -111,18 +113,18 @@ class Nacos
* @return mixed|string|null
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function getToken($new = false)
private static function getToken($new = false)
{
$key = 'nacos:sync:get:token';
$token = Nacos::Nacosget($key);;
$token = Nacos::NacosGet($key);;
if (empty($token) || $new) {
$user = self::$configs['ACCOUNT'];
$pass = self::$configs['NACOS_PWD'];
$url = self::$configs['NACOS_URL'].'/nacos/v1/auth/login';
$data = ['username' => $user, 'password' =>$pass];
$token = $this->login($data ,$url);
$token = self::login($data ,$url);
$logs = '获取token: ' . $token;
$this->info($logs);
self::info($logs);
}
Nacos::NacosPut($key, $token);
return $token;
......@@ -133,7 +135,7 @@ class Nacos
* @param $url
* @return mixed|string
*/
public function getConfigRequest($url){
public static function getConfigRequest($url){
// 创建一个cURL资源
$curl = curl_init();
curl_setopt_array($curl, array(
......@@ -152,10 +154,17 @@ class Nacos
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err){
$this->info($err);
self::info($err);
}
curl_close($curl);
$data = json_decode($response,true);
if (isset($data['status']) && $data['status'] == 403){
throw new Exception('token过期',403);
}
if (isset($data['code']) && $data['code'] !== 0){
self::info('获取配置返回结果:'.$response);
return '';
}
return $data['data'] ?? '';
}
......@@ -165,7 +174,7 @@ class Nacos
* @return mixed|string|void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function login($data,$url)
private static function login($data,$url)
{
try {
$curl = curl_init();
......@@ -185,14 +194,14 @@ class Nacos
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err){
$this->info($err);
self::info($err);
}
curl_close($curl);
// 处理响应
$loginDataArr = json_decode($response,true);
return $loginDataArr['accessToken'] ?? '';
} catch (\Exception $e) {
$this->info($e->getMessage());
self::info($e->getMessage());
}
}
......@@ -202,7 +211,7 @@ class Nacos
* @return mixed|string
*/
public static function NacosGet($key){
$path = Nacos::getPath('/.nacos.cache');
$path =self::getPath(sys_get_temp_dir(), '/nacos.cache-'.md5(self::$configs['GROUP']));
$data = json_decode(
file_get_contents($path),
true,
......@@ -220,7 +229,7 @@ class Nacos
* @return void
*/
public static function NacosPut($key,$value){
$path = Nacos::getPath('/.nacos.cache');
$path = self::getPath(sys_get_temp_dir(), '/nacos.cache-'.md5(self::$configs['GROUP']));
$data = json_decode(
file_get_contents($path),
true,
......@@ -237,9 +246,12 @@ class Nacos
* @param $msg
* @return void
*/
private function info($msg)
private static function info($msg)
{
Log::info($msg);
self::writeLog($msg);
if (!is_string($msg)){
$msg = $msg['msg'];
}
echo $msg."\n";
}
......@@ -248,23 +260,55 @@ class Nacos
* @param $fileName
* @return string
*/
public static function getPath($fileName){
return base_path().$fileName;
public static function getPath($path,$fileName){
if (!file_exists($path)) {
mkdir($path, 0775, true);
touch($fileName);
}
if (!file_exists($path.$fileName)) {
touch($fileName);
}
return $path.$fileName;
}
/**
* 获取nacos
* @return void
* @return bool
*/
public static function configure()
public static function configure($options)
{
$path = Nacos::getPath('/.env.nacos');
try {
$data = parse_ini_file($path);
} catch (\Exception $ex){
\Log::info($ex->getMessage());
$data = [];
$envNacos = $options['env.nacos'];
self::$basePath = $options['base_path'];
$file = self::$basePath.$envNacos;
$data = parse_ini_file($file);
if (empty($data)) {
self::info( '输入参数有误:'.$file);
return false;
}
Nacos::$configs = $data;
return true;
}
/**
* 写入日志
* @return void
*/
public static function writeLog($logData){
$logFile = '/nacos-'.date('Y-m-d').'.log';
$path = self::getPath(sys_get_temp_dir(),$logFile);
$data = json_decode(
file_get_contents($path),
true,
);
if (!is_string($logData)){
$logData = json_encode($logData,);
}
$data[] = $logData;
file_put_contents(
$path,
json_encode($data),
);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment