前言
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的概念,当出现网络闪断、重连,会出现漏消息的问题。 远程监听这里我自己实现了一个,可以参考我这篇文章