使用Viper讀取Nacos配置(開源)
開源
https://github.com/yoyofxteam/nacos-viper-remote
一、前言
目前Viper支持的Remote遠程讀取配置如 etcd, consul;目前還沒有對Nacos進行支持,本文中將開源一個Nacos的Viper支持庫, 開源地址在文章的最下方.
實現這個倉庫的主要目的是為了,最終集成到我們的yoyogo框架中。
二、什么是Viper
Viper是適用於Go應用程序的完整配置解決方案。它被設計用於在應用程序中工作,並且可以處理所有類型的配置需求和格式。
2.1 它支持以下特性:
- 設置默認值
- 從JSON、TOML、YAML、HCL、envfile和Java properties格式的配置文件讀取配置信息
- 實時監控和重新讀取配置文件(可選)
- 從環境變量中讀取
- 從遠程配置系統remote(etcd或Consul)讀取並監控配置變化
- 從命令行參數讀取配置
- 從buffer讀取配置
- 顯式配置值
2.2 讀取本地文件
viper.SetConfigFile("./config.yaml") // 指定配置文件路徑
viper.SetConfigName("config") // 配置文件名稱(無擴展名)
viper.SetConfigType("yaml") // 如果配置文件的名稱中沒有擴展名,則需要配置此項
viper.AddConfigPath("/etc/appname/") // 查找配置文件所在的路徑
viper.AddConfigPath("$HOME/.appname") // 多次調用以添加多個搜索路徑
viper.AddConfigPath(".") // 還可以在工作目錄中查找配置
err := viper.ReadInConfig() // 查找並讀取配置文件
if err != nil { // 處理讀取配置文件的錯誤
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
本篇文章重點着重於remote部分,Nacos的支持.
Viper remote
在Viper中啟用遠程支持,需要在代碼中匿名導入viper/remote這個包。
import _ "github.com/spf13/viper/remote"
通過remote,Viper將支持讀取從Key/Value存儲( 例如etcd或Consul或本文中的Nacos ).
Viper加載配置值的優先級
磁盤上的配置文件 > 命令行標志位 > 環境變量 > 遠程Key/Value存儲 > 默認值 。
Nacos 支持
引用我們的開源庫 https://github.com/yoyofxteam/nacos-viper-remote
import (
"github.com/spf13/viper"
remote "github.com/yoyofxteam/nacos-viper-remote"
)
在項目中使用:
runtime_viper := viper.New()
// 配置 Viper for Nacos 的遠程倉庫參數
remote.SetOptions(&remote.Option{
Url: "localhost", // nacos server 多地址需要地址用;號隔開,如 Url: "loc1;loc2;loc3"
Port: 80, // nacos server端口號
NamespaceId: "public", // nacos namespace
GroupName: "DEFAULT_GROUP", // nacos group
Config: remote.Config{ DataId: "config_dev" }, // nacos DataID
Auth: nil, // 如果需要驗證登錄,需要此參數
})
err := remote_viper.AddRemoteProvider("nacos", "localhost", "")
remote_viper.SetConfigType("yaml")
_ = remote_viper.ReadRemoteConfig() //sync get remote configs to remote_viper instance memory . for example , remote_viper.GetString(key)
_ = remote_viper.WatchRemoteConfigOnChannel() //異步監聽Nacos中的配置變化,如發生配置更改,會直接同步到 viper實例中。
appName := remote_viper.GetString("key") // sync get config by key
fmt.Println(appName)
// 這里不是必須的,只為了監控Demo中的配置變化,並打印出來
go func() {
for {
time.Sleep(time.Second * 30) // 每30秒檢查配置是否發生變化
appName = config_viper.GetString("yoyogo.application.name")
fmt.Println(appName)
}
}()
最后
實現這個倉庫的主要目的是為了,最終集成到我們的yoyogo框架中。
本文提及的開源庫地址:
nacos-viper-remote
https://github.com/yoyofxteam/nacos-viper-remote
yoyogo
https://github.com/yoyofx/yoyogo
🦄🌈 YoyoGo is a simple, light and fast , dependency injection based micro-service framework written in Go. Support Nacos ,Consoul ,Etcd ,Eureka ,kubernetes.