首頁  >  文章  >  後端開發  >  一文詳解配置中心nacos的安裝使用方法

一文詳解配置中心nacos的安裝使用方法

藏色散人
藏色散人轉載
2022-11-14 16:44:542991瀏覽

本文由golang教學專欄為大家介紹關於配置中心“nacos ”,下面將以golang的角度來了解配置中心,naco 的安裝以及如何用nacos做配置,讀取nacos中配置文件等等,希望對需要的朋友有幫助!

一文詳解配置中心nacos的安裝使用方法

什麼是組態中心

用來統一管理專案中所有設定的系統。雖然聽起來很簡單,但也不要小瞧了這個模組。如果一個中型網路項目,不採用配置中心的模式,一大堆的各類配置項,各種不定時的修改需求,一定會讓開發同學非常頭疼且管理十分混亂。

配置中心的服務流程如下: 使用者在配置中心更新設定資訊。服務 A 和服務 B 及時得到配置更新通知,從配置中心取得配置。總得來說,配置中心就是一種統一管理各種應用配置的基礎服務元件。

在系統架構中,配置中心是整個微服務基礎架構體系中的一個元件,它的功能看起來並不起眼,無非就是配置的管理和訪問,但它是整個微服務架構中不可或缺的一環。

nacos 是什麼

Nacos

Nacos 是Naming and Configuration Service 的縮寫,從名字上能看出它重點關注的兩個領域是Naming 即註冊中心和Configuration 配置中心。

業務上的配置,功能開關,服務治理上對弱依賴的降級,甚至資料庫的密碼等,都可能用到動態配置中心。在沒有專門的配置中心元件時,我們使用硬編碼、或設定檔、或資料庫、快取等方式來解決問題。硬編碼修改配置時需要重新編譯打包,設定檔需要重啟應用,資料庫受限於效能,快取喪失了及時性。

Nacos 的設定模型

namespace group dataId 唯一確定一個設定

  • namespace:與client 綁定,一個clinet 對應到一個namespace,可用來隔離環境或區分租用戶

  • group:分組,區分業務

  • dataId:配置的id

來看看是如何在實際場景中使用的

例如:一個電商網站其中有這幾個模組:使用者模組、商品模組、訂單模組、庫存模組

這幾個模組都需要進行配置且它們的配置不同,這是我們為每個模組做一個namespace, 每個模組都需要有

開發階段的配置,和上線後的配置,使用我們使用dev, 和pro 兩個分組來進行區分,對於dataId,不管是dev 還是

pro 都必須填寫。

Nacos 的安裝

這裡我們直接使用docker 進行安裝

Nacos 的安裝(docker)

docker run --name nacos-standalone -e MODE=standalone -e JVM_XMS=512m -e JVM_XMX=512m -e JVM_XMN=256m -p 8848:8848 -d nacos/nacos-server:latest

存取:192.168.1.103:8848/nacos/index.html 使用者名稱/ 密碼:nacos/nacos

##設定開機啟動:

docker container update --restart=always xxx

用nacos 做設定

nacos 成功啟動後存取:192.168.1.103:8848/nacos/index.html

可以建立namespace, 我們新建一個使用者模組user , 建立成功後可以看到有對應的id, 例如:7ae18f62-e2b9-48bd-bff2-a49e7443f5bc

然後我們在user 命名空間下新建一個配置文件,並填寫對應的名稱(dataId) 和分組,這裡我們新建一個josn 的配置文件:

{
    "name": "user-web",
    "host": "10.2.106.169",
    "port": 9091,
    "tags":["iceymoss", "goods", "golang", "web"],
    "user_srv":{
        "name": "user-srv",
        "host": "10.2.106.169",
        "port": 8081
    },
    "jwt":{
        "key": "dfijdfjidhfjijdfbdfdFwohPd6XmVCdnQi"
    },
    "sms":{
        "key": "mykey",
        "secret": "mysecret"
    },
    "params":{
        "sign_name": "生鲜小店",
        "code": "SMS_244610581"
    },
    "redis":{
        "host": "127.0.0.1",
        "port": 6379,
        "expir": 300
    },
    "verify":{
        "width": 5
    },
    "consul":{
        "host": "10.2.106.169",
        "port": 8500
    },
    "tracing":{
        "host": "127.0.0.1",
        "port": 6831,
        "name": "shopping"
    }
}

這樣整個設定檔就配置完成了

讀取nacos 中設定檔

拉取依賴

我們使用go 來讀取配置文件,使用需要拉取nacos 的sdk:

go get github.com/nacos-group/nacos-sdk-go/clients
go get github.com/nacos-group/nacos-sdk-go/common/constant
go get github.com/nacos-group/nacos-sdk-go/vo

讀取配置##在讀取配置之前我們先寫一個用來做設定映射的結構體

目錄結構:

nacos_test
├── config
│   └── config.go
└── main.go

寫config 時需要注意的是我們需要保持tag 名稱和設定檔中的名稱一致

package config

//UserSerConfig 映射用户配置
type UserSerConfig struct {
    Name string `mapstructure:"name" json:"name"`
    Host string `mapstructure:"host" json:"host"`
    Port int    `mapstructure:"port" json:"port"`
}

//JWTConfig 映射token配置
type JWTConfig struct {
    SigningKey string `mapstructure:"key" json:"key"`
}

//AliSmsConfig 阿里秘钥
type AliSmsConfig struct {
    Apikey    string `mapstructure:"key" json:"key"`
    ApiSecret string `mapstructure:"secret" json:"secret"`
}

//ParamsConfig 短信模板配置
type ParamsConfig struct {
    SignName     string `mapstructure:"sign_name" json:"sign_name"`
    TemplateCode string `mapstructure:"code" json:"code"`
}

//RedisConfig redis数据库配置
type RedisConfig struct {
    Host  string `mapstructure:"host" json:"host"`
    Port  int    `mapstructure:"port" json:"port"`
    Expir int    `mapstructure:"expir" json:"expir"`
}

//Verifier 手机验证长度
type Verifier struct {
    Width int `mapstructure:"width" json:"width"`
}

type ConsulConfig struct {
    Host string `mapstructure:"host" json:"host"`
    Port int    `mapstructure:"port" json:"port"`
}

//ServerConfig  映射服务配置
type ServerConfig struct {
    Name        string        `mapstructure:"name" json:"name"`
    Port        int           `mapstructure:"port" json:"port"`
    UserSerInfo UserSerConfig `mapstructure:"user_srv" json:"user_srv"`
    JWTInfo     JWTConfig     `mapstructure:"jwt" json:"jwt"`
    AliSms      AliSmsConfig  `mapstructure:"sms" json:"sms"`
    Params      ParamsConfig  `mapstructure:"params" json:"params"`
    Redis       RedisConfig   `mapstructure:"redis" json:"redis"`
    Verify      Verifier      `mapstructure:"verify" json:"verify"`
    ConsulInfo  ConsulConfig  `mapstructure:"consul" json:"consul"`
}

下面進行設定檔讀取:

package main

import (
    "StudyGin/nacos/config"
    "encoding/json"
    "fmt"

    "github.com/nacos-group/nacos-sdk-go/clients"
    "github.com/nacos-group/nacos-sdk-go/common/constant"
    "github.com/nacos-group/nacos-sdk-go/vo"
)

func main() {
    //服务端配置, nacos运行的socket
    sc := []constant.ServerConfig{
        {
            IpAddr: "10.2.81.102",
            Port:   8848,
        },
    }

    //客服端配置
    cc := constant.ClientConfig{
        NamespaceId:         "7ae18f62-e2b9-48bd-bff2-a49e7443f5bc", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId
        TimeoutMs:           5000,
        NotLoadCacheAtStart: true,
        LogDir:              "tmp/nacos/log",
        CacheDir:            "tmp/nacos/cache",
        //RotateTime:          "1h",
        //MaxAge:              3,
        LogLevel: "debug",
    }

    configClient, err := clients.CreateConfigClient(map[string]interface{}{
        "serverConfigs": sc,
        "clientConfig":  cc,
    })
    if err != nil {
        panic(err)
    }

    //获取配置
    content, err := configClient.GetConfig(vo.ConfigParam{
        DataId: "user-web.json",
        Group:  "dev"})

    if err != nil {
        panic(err)
    }
    Config := &config.ServerConfig{}

  //将配置信息读取到config.ServerConfig{}对象中
    err = json.Unmarshal([]byte(content), &Config)
    if err != nil {
        panic(err)
    }
    fmt.Println(Config)

}

輸出:

&{user-web 9091 {user-srv 10.2.106.169 8081} {dfijdfjidhfjijdfbdfdFwohPd6XmVCdnQi} {mykey mysecret} {生鲜小店 SMS_244610581} {127.0.0.1 6379 300} {5} {10.2.106.1600}}

當然設定中心和viper 都提供即時監控設定

可以這樣寫:

    //监听配置变化
    err = configClient.ListenConfig(vo.ConfigParam{
        DataId: "user-web",
        Group:  "DEV",
        OnChange: func(namespace, group, dataId, data string) {
            fmt.Println("配置文件变化")
            fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
        },
    })
    time.Sleep(3000 * time.Second)

以上是一文詳解配置中心nacos的安裝使用方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除