您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

关于Nacos解决laravel多环境下配置切换

2024/11/9 17:58:37发布20次查看
下面由laravel教程栏目给大家介绍nacos 解决 laravel 多环境下配置切换的方法 ,希望对需要的朋友有所帮助!
前言对于应用程序运行的环境来说,不同的环境有不同的配置通常是很有用的。例如,你可能希望在本地使用的缓存驱动不同于生产服务器所使用的缓存驱动。
痛点.env 配置不能区分多环境(开发,测试,生产).env 配置共享太麻烦(团队局域网环境)配置不能实时管理,增删改配置
自动化部署配置 .env 文件过于繁琐
nacos 简介nacos 是阿里巴巴最新开源的项目,核心定位是 “一个更易于帮助构建云原生应用的动态服务发现、配置和服务管理平台”,项目地址:nacos.io/zh-cn/
应用这里主要使用了 nacos 的配置管理,并没有使用到动态服务等功能。原理也很简单,通过接口直接修改 .env 文件。nacos 服务可以直接使用使用阿里云提供的 应用配置管理,无须安装。链接如下: acmnext.console.aliyun.com/
代码<?phpnamespace app\console\commands;use guzzlehttp\client;use illuminate\console\command;use illuminate\support\facades\artisan;use illuminate\support\facades\validator;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        ));    }}
使用示例注册账号,开通服务这些就不说了.env 添加配置项 nacos_access_key nacos_secret_key 等php artisan nacos 0 获取配置php artisan nacos 1 发布配置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 忘记加配置项,共享配置也不是件麻烦事了,自动部署也不需要频繁的改动配置了。                        
以上就是关于nacos解决laravel多环境下配置切换的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product