栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang配置库viper使用教程

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang配置库viper使用教程

golang配置库viper使用教程
  • 前言
  • 一、配置文件加载
  • 二、配置文件热更新
  • 三、命令行参数绑定
  • 四、环境变量
  • 五、默认值设置
  • 六、远程监听

前言
  • viper作为golang的配置库:
    • 多种格式配置文件
    • 配置优先级覆盖(个人觉得最好用的地方):
      • overrides:显示设置
      • flags:命令行参数
      • env. variables:环境变量(容器服务非常好用)
      • config file:配置文件
      • key/value store:远程kv数据库
      • defaults:默认值
  • 这里简单地介绍一下库使用
一、配置文件加载
  • 目前支持的配置文件格式:
// 见viper源码文件viper.go
……
// SupportedExts are universally supported extensions.
var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "dotenv", "env", "ini"}
……
  • 使用方式:
// 直接设置配置文件路径
viper.SetConfigFile(cfgFile)

// 以下两个连用,目的是加载多个配置文件
// 设置配置文件目录
viper.AddConfigPath(home)
// 设置配置文件名(不带后缀)
viper.SetConfigName(".scanService")
二、配置文件热更新
  • 使用方式:
// 监听配置文件
viper.WatchConfig()
// 配置文件更新回调函数
viper.OnConfigChange(func(e fsnotify.Event) {
	fmt.Println("config file has changed")
})
  • 这里有个坑,监听文件设置不当,可能导致文件一次更新,触发多次配置更新+回调,造成的后果就是,n次通知之间,配置的值不安全,可能拿到空值!,具体原因、解决办法可以看下这篇文章
  • 本质原因就是这段代码导致的:
// 见viper源码文件viper.go
func (v *Viper) WatchConfig() {
…………
// we only care about the config file with the following cases:
// 1 - if the config file was modified or created
// 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement)
const writeOrCreateMask = fsnotify.Write | fsnotify.Create
if (filepath.Clean(event.Name) == configFile &&
	event.Op&writeOrCreateMask != 0) ||
	(currentConfigFile != "" && currentConfigFile != realConfigFile) {
		…………
	}
…………
}
  • 解决办法(设置多重软链):
# viper.SetConfigFile("/tmp/config.yaml")
# viper.WatchConfig()
[root@0314920da160 conf]# ll /tmp
total 32
drwxr-xr-x 2 root root  43 Jul 27 10:47 1.2.0
lrwxrwxrwx 1 root root  15 Jul 27 10:47 cfg_in_use -> 1.2.0
lrwxrwxrwx 1 root root  32 Jul 27 10:47 config.yaml -> cfg_in_use/config.yaml
…………
三、命令行参数绑定
  • 使用方式:
// 这里引入cobra来介绍
// var rootCmd *cobra.Command
rootCmd.PersistentFlags().Int("log-file-size", 100, "log file size(MB)")
viper.BindPFlag("LOGGER.LOGGER_FILE_MAXSIZE", rootCmd.PersistentFlags().Lookup("log-file-size"))
四、环境变量
  • 使用方式:
viper.AutomaticEnv()
五、默认值设置
viper.SetDefault("LOGGER.LOGGER_FILE_MAXSIZE", 100)
六、远程监听
  • 这里个人觉得不是很好用,而且存在漏消息的风险,由于没有引入etcd revision的概念,当出现网络闪断、重连,会出现漏消息的问题。
  • 远程监听这里我自己实现了一个,可以参考我这篇文章《一个基于分布式系统的etcd监听者》
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908266.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号