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监听者》
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值