viper - 配置文件管理

该代码示例展示了在Go中如何使用viper库来读取和管理配置文件,包括yaml格式的本地配置文件读取、动态监听文件变化并更新配置、以及远程配置提供者(如Consul)的集成。程序会初始化配置,监听配置文件变化,并在配置变化时更新全局变量。此外,还展示了如何设置和读取Consul的KV存储中的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"log"
	"os"
	"path"
	"time"
)

var Cfg EnvSD

type EnvSD struct {
	Mysql  Mysql  `mapstructure:"mysql"`
	Consul Consul `mapstructure:"consul"`
}

type Mysql struct {
	Conn string                   `mapstructure:"conn"`
	Desc string                   `mapstructure:"desc"`
	Auth `mapstructure:",squash"` // viper 包匿名嵌套标识符为 squash
}

type Consul struct {
	Addr string `mapstructure:"addr"`
	Desc string `mapstructure:"desc"`
	Auth `mapstructure:",squash"`
}

type Auth struct {
	User     string `mapstructure:"user"`
	Password string `mapstructure:"password"`
}

func initConf() {

	// 获取项目目录
	exePath, _ := os.Executable()
	projectPath := path.Dir(exePath)

	viper.NewWithOptions(viper.KeyDelimiter("->")) // 修改 viper 的分隔符
	viper.AddConfigPath(projectPath)               // 配置文件路径
	viper.SetConfigName("conf.yaml")               // 配置文件名
	viper.SetConfigType("yaml")                    // 配置文件类型

	// 读取
	if err := viper.ReadInConfig(); err != nil {
		log.Fatalln("[pkg.class.func.read config failed] ", err.Error())
	}

	// 反序列化
	viper.Unmarshal(&Cfg)

	fmt.Printf("%+v\n", Cfg)
}

// watchFileUpdateConf 监听配置文件, 更新到Conf实例
func watchFileUpdateConf() {

	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {

		// 更新可变的配置内容
		viper.Unmarshal(&Cfg)

		// 记录日志
		log.Println(e.String())
		log.Printf("%+v\n", Cfg)
	})
}

func main() {

	// 读取配置文件,解码到结构体
	initConf()

	// 监听文件变化
	go watchFileUpdateConf()

	// 模拟结构体发生改变时更新到文件, 将字段反序列化到结构体,存入文件
	viper.Set("consul.addr", "9.9.9.9")
	viper.UnmarshalKey("consul.addr", "9.9.9.9")
	viper.WriteConfig()

	// 模拟hang住
	time.Sleep(60 * time.Second)
}

远程读取 consul kv 库

package main

import (
	"fmt"
	"github.com/spf13/viper"

	_ "github.com/spf13/viper/remote"
)

func main() {

	err := viper.AddRemoteProvider("consul", "http://service-epoch-cozzc:8500", "/test/server.json")
	if err != nil {
		fmt.Println(err.Error())
	}

	viper.SetConfigType("json") // Need to explicitly set this to json
	err = viper.ReadRemoteConfig()
	if err != nil {
		fmt.Println(err.Error())
	}

	fmt.Println(viper.GetString("server.ip"))
	fmt.Println(viper.GetString("server.port"))
}


watch机制

  • 本地是用ionotify实现的
  • 远程暂时只支持etcd, 使用轮询实现

参考链接

  • http://www.manongjc.com/detail/54-fdqfrlykcewpwsq.html)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值