站長資訊網
        最全最豐富的資訊網站

        關于Nacos解決laravel多環境下配置切換

        下面由Laravel教程欄目給大家介紹Nacos 解決 laravel 多環境下配置切換的方法 ,希望對需要的朋友有所幫助!

        前言

        對于應用程序運行的環境來說,不同的環境有不同的配置通常是很有用的。例如,你可能希望在本地使用的緩存驅動不同于生產服務器所使用的緩存驅動。

        痛點

        • .env 配置不能區分多環境(開發,測試,生產)
        • .env 配置共享太麻煩(團隊局域網環境)
        • 配置不能實時管理,增刪改配置

        • 自動化部署配置 .env 文件過于繁瑣

        Nacos 簡介

        Nacos 是阿里巴巴最新開源的項目,核心定位是 “一個更易于幫助構建云原生應用的動態服務發現、配置和服務管理平臺”,項目地址:nacos.io/zh-cn/

        應用

        這里主要使用了 Nacos 的配置管理,并沒有使用到動態服務等功能。原理也很簡單,通過接口直接修改 .env 文件。Nacos 服務可以直接使用使用阿里云提供的 應用配置管理,無須安裝。鏈接如下: acmnext.console.aliyun.com/

        代碼

        <?php  namespace AppConsoleCommands;use GuzzleHttpClient;use IlluminateConsoleCommand;use IlluminateSupportFacadesArtisan;use IlluminateSupportFacadesValidator;class NacosTools extends Command{     /**      * The name and signature of the console command.      *      * @var string      */     protected $signature = 'nacos {action?}';      private $accessKey;     private $secretKey;     private $endpoint = 'acm.aliyun.com';     private $namespace;     private $dataId;     private $group;     private $port = 8080;     private $client;      private $serverUrl;      /**      * The console command description.      *      * @var string      */     protected $description = 'Nacos 管理工具';      /**      * Create a new command instance.      *      * @return void      */     public function __construct()     {         parent::__construct();     }      /**      * Execute the console command.      *      * @return mixed      * @throws Exception      */     public function handle()     {         $this->accessKey = env('NACOS_ACCESS_KEY');         $this->secretKey = env('NACOS_SECRET_KEY');         $this->endpoint = env('NACOS_ENDPOINT');         $this->namespace = env('NACOS_NAMESPACE');         $this->port = env('NACOS_PORT', $this->port);         $this->dataId = env('NACOS_DATA_ID');         $this->group = env('NACOS_GROUP');          if (!$this->validate()) {             $this->error('請檢查配置參數');              return;         }          $this->client = new Client(['verify' => false]);          $this->info('Nacos 配置工具');          $actions = [             '獲取配置',             '發布配置',             '刪除配置',         ];          if (is_null($this->argument('action'))) {             $action = $this->choice('請選擇操作',                 $actions,                 $actions[0]);         } else {             if (in_array($this->argument('action'), array_keys($actions))) {                 $action = $actions[$this->argument('action')];             } else {                 $action = $this->choice('請選擇操作',                     $actions,                     $actions[0]);             }         }          $this->do($action);     }      public function do($action = '獲取配置')     {         switch ($action) {             default:             case '獲取配置':                 $config = $this->getConfig();                  if ($config) {                     file_put_contents('.env', $config);                     $this->info('獲取配置成功');                 } else {                     $this->error('獲取配置失敗');                 }                  break;             case '發布配置':                 if ($this->publishConfig()) {                     $this->info('發布配置成功');                 } else {                     $this->error('發布配置失敗');                 }                  break;              case '刪除配置':                 if ($this->removeConfig()) {                     $this->info('刪除配置成功');                 } else {                     $this->error('刪除配置失敗');                 }                  break;         }     }      /**      * 驗證配置參數      *      * Date: 2020/6/10      * @return bool      */     private function validate()     {         $data = [             'accessKey' => $this->accessKey,             'secretKey' => $this->secretKey,             'endpoint'  => $this->endpoint,             'namespace' => $this->namespace,             'dataId'    => $this->dataId,             'group'     => $this->group,         ];          $rules = [             'accessKey' => 'required',             'secretKey' => 'required',             'endpoint'  => 'required',             'namespace' => 'required',             'dataId'    => 'required',             'group'     => 'required',         ];          $messages = [             'accessKey.required' => '請填寫`.env`配置 NACOS_ACCESS_KEY',             'secretKey.required' => '請填寫`.env`配置 NACOS_SECRET_KEY',             'endpoint.required'  => '請填寫`.env`配置 NACOS_ENDPOINT',             'namespace.required' => '請填寫`.env`配置 NACOS_NAMESPACE',             'dataId.required'    => '請填寫`.env`配置 NACOS_DATA_ID',             'group.required'     => '請填寫`.env`配置 NACOS_GROUP',         ];          $validator = Validator::make($data, $rules, $messages);          if ($validator->fails()) {             foreach ($validator->getMessageBag()->toArray() as $item) {                 foreach ($item as $value) {                     $this->error($value);                 }             }              return false;         }          return true;     }      /**      * 獲取配置      *      * Date: 2020/6/10      * @return bool      */     private function getConfig()     {         $acmHost = str_replace(['host', 'port'], [$this->getServer(), $this->port],             'http://host:port/diamond-server/config.co');          $query = [             'dataId' => urlencode($this->dataId),             'group'  => urlencode($this->group),             'tenant' => urlencode($this->namespace),         ];          $headers = $this->getHeaders();          $response = $this->client->get($acmHost, [             'headers' => $headers,             'query'   => $query,         ]);          if ($response->getReasonPhrase() == 'OK') {             return $response->getBody()->getContents();         } else {             return false;         }     }      /**      * 發布配置      *      * Date: 2020/6/10      * @return bool      */     public function publishConfig()     {         $acmHost = str_replace(             ['host', 'port'],             [$this->getServer(), $this->port],             'http://host:port/diamond-server/basestone.do?method=syncUpdateAll');          $headers = $this->getHeaders();          $formParams = [             'dataId'  => urlencode($this->dataId),             'group'   => urlencode($this->group),             'tenant'  => urlencode($this->namespace),             'content' => file_get_contents('.env'),         ];          $response = $this->client->post($acmHost, [             'headers'     => $headers,             'form_params' => $formParams,         ]);          $result = json_decode($response->getBody()->getContents(), 1);          return $result['message'] == 'OK';     }      public function removeConfig()     {         $acmHost = str_replace(['host', 'port'], [$this->getServer(), $this->port],             'http://host:port/diamond-server//datum.do?method=deleteAllDatums');          $headers = $this->getHeaders();          $formParams = [             'dataId' => urlencode($this->dataId),             'group'  => urlencode($this->group),             'tenant' => urlencode($this->namespace),         ];          $response = $this->client->post($acmHost, [             'headers'     => $headers,             'form_params' => $formParams,         ]);          $result = json_decode($response->getBody()->getContents(), 1);          return $result['message'] == 'OK';     }      /**      * 獲取配置服務器地址      *      * Date: 2020/6/10      * @return string      */     private function getServer()     {         if ($this->serverUrl) {             return $this->serverUrl;         }          $serverHost = str_replace(             ['host', 'port'],             [$this->endpoint, $this->port],             'http://host:port/diamond-server/diamond');          $response = $this->client->get($serverHost);          return $this->serverUrl = rtrim($response->getBody()->getContents(), PHP_EOL);     }      /**      * 獲取請求頭      *      * Date: 2020/6/10      * @return array      */     private function getHeaders()     {         $headers = [             'Diamond-Client-AppName' => 'ACM-SDK-PHP',             'Client-Version'         => '0.0.1',             'Content-Type'           => 'application/x-www-form-urlencoded; charset=utf-8',             'exConfigInfo'           => 'true',             'Spas-AccessKey'         => $this->accessKey,             'timeStamp'              => round(microtime(true) * 1000),         ];          $headers['Spas-Signature'] = $this->getSign($headers['timeStamp']);          return $headers;     }      /**      * 獲取簽名      *      * @param $timeStamp      * Date: 2020/6/10      * @return string      */     private function getSign($timeStamp)     {         $signStr = $this->namespace.'+';          if (is_string($this->group)) {             $signStr .= $this->group."+";         }          $signStr = $signStr.$timeStamp;          return base64_encode(hash_hmac(             'sha1',             $signStr,             $this->secretKey,             true         ));     }}

        使用示例

        1. 注冊賬號,開通服務這些就不說了
        2. .env 添加配置項 NACOS_ACCESS_KEY NACOS_SECRET_KEY
        3. php artisan nacos 0 獲取配置
        4. php artisan nacos 1 發布配置
        5. php artisan nacos 2 刪除配置

        配置項說明

        NACOS_ENDPOINT= #nacos節點 如使用阿里云服務 即:acm.aliyun.comNACOS_DATA_ID= #項目ID 可以填項目名NACOS_GROUP= #分組ID 這里可以用于區分環境 建議 local production test 等值NACOS_NAMESPACE= # 命名空間 建議用來區分服務器 server-A server-BNACOS_ACCESS_KEY= #阿里云access_key 建議使用子賬號access_keyNACOS_SECRET_KEY= #阿里云secret_key 建議使用子賬號secret_key

        總結

        使用 nacos 后,再也不用擔心 .env.example 忘記加配置項,共享配置也不是件麻煩事了,自動部署也不需要頻繁的改動配置了。

        贊(0)
        分享到: 更多 (0)
        網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
        主站蜘蛛池模板: 国产精品V亚洲精品V日韩精品| 精品国偷自产在线视频| 99re热这里只有精品视频中文字幕| 国产精品一香蕉国产线看观看 | 无码国内精品久久人妻蜜桃| 国产精品内射久久久久欢欢| 99久久精品影院老鸭窝| 欧美肥屁VIDEOSSEX精品| 欧美精品色婷婷五月综合 | 成人午夜精品视频在线观看 | 国产精品永久免费视频| 99久久精品毛片免费播放| 日本VA欧美VA精品发布| 亚洲精品国精品久久99热| 国产在线精品一区二区高清不卡 | 国产精品爽爽ⅴa在线观看| 成人久久精品一区二区三区| 精品无码一区二区三区亚洲桃色| 亚洲日韩国产AV无码无码精品| 国产亚洲精品免费视频播放| 永久免费精品视频| 精品无人区麻豆乱码1区2区| 国产乱码精品一区二区三区中文 | AAA级久久久精品无码片| 欧美肥屁VIDEOSSEX精品| 熟妇无码乱子成人精品| 亚洲AV无码久久精品狠狠爱浪潮 | 无码国产亚洲日韩国精品视频一区二区三区 | 亚洲国产av无码精品| 热久久国产欧美一区二区精品| 国模精品一区二区三区| 国产精品免费久久久久久久久 | 91久久婷婷国产综合精品青草| 国产精品99久久99久久久| 精品无码AV一区二区三区不卡 | 久久精品二区| 久久99精品免费一区二区| 久热这里只有精品99国产6| 蜜桃麻豆www久久国产精品| 午夜精品一区二区三区在线视 | 亚洲精品欧美二区三区中文字幕 |