脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - 详解go基于viper实现配置文件热更新及其源码分析

详解go基于viper实现配置文件热更新及其源码分析

2020-07-11 11:19_雨落山岚 Golang

这篇文章主要介绍了详解go基于viper实现配置文件热更新及其源码分析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

go第三方库 github.com/spf13/viper  实现了对配置文件的读取并注入到结构中,好用方便。

其中以

?
1
2
3
4
5
6
viperInstance := viper.New()    // viper实例
viperInstance.WatchConfig()
viperInstance.OnConfigChange(func(e fsnotify.Event) {
    log.Print("Config file updated.")
    viperLoadConf(viperInstance)  // 加载配置的方法
})

可实现配置的热更新,不用重启项目新配置即可生效(实现热加载的方法也不止这一种,比如以文件的上次修改时间来判断等)。

为什么这么写?这样写为什么就能立即生效?基于这两个问题一起来看看viper是怎样实现热更新的。

上面代码的核心一共两处:WatchConfig()方法、OnConfigChange()方法。WatchConfig()方法用来开启事件监听,确定用户操作文件后该文件是否可正常读取,并将内容注入到viper实例的config字段,先来看看WatchConfig()方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
func (v *Viper) WatchConfig() {
    go func() {
      // 建立新的监视处理程序,开启一个协程开始等待事件
      // 从I/O完成端口读取,将事件注入到Event对象中:Watcher.Events
        watcher, err := fsnotify.NewWatcher() 
        if err != nil {
            log.Fatal(err)
        }
        defer watcher.Close()
 
        // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
        filename, err := v.getConfigFile() 
        if err != nil {
            log.Println("error:", err)
            return
        }
 
        configFile := filepath.Clean(filename)    //配置文件E:\etc\bizsvc\config.yml
        configDir, _ := filepath.Split(configFile)  // E:\etc\bizsvc\
 
        done := make(chan bool)
        go func() {
            for {
                select {
        // 读取的event对象有两个属性,Name为E:\etc\bizsvc\config.yml,Op为write(对文件的操作)
                case event := <-watcher.Events:
        // 清除内部的..和他前面的元素,清除当前路径.,用来判断操作的文件是否是configFile
                    if filepath.Clean(event.Name) == configFile {
        // 如果对该文件进行了创建操作或写操作
                        if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
                            err := v.ReadInConfig()
                            if err != nil {
                                log.Println("error:", err)
                            }
                            v.onConfigChange(event)
                        }
                    }
                case err := <-watcher.Errors:
         // 有错误将打印
                    log.Println("error:", err)
                }
            }
        }()
 
        watcher.Add(configDir)
        <-done
    }()
}

其中,fsnotify是用来监控目录及文件的第三方库;  watcher, err := fsnotify.NewWatcher() 用来建立新的监视处理程序,它会开启一个协程开始等待读取事件,完成 从I / O完成端口读取任务,将事件注入到Event对象中,即Watcher.Events;

详解go基于viper实现配置文件热更新及其源码分析

执行v.ReadInConfig()后配置文件的内容将重新读取到viper实例中,如下图:

详解go基于viper实现配置文件热更新及其源码分析

执行完v.ReadInConfig()后,config字段的内容已经是用户修改的最新内容了;

其中这行v.onConfigChange(event)的onConfigChange是核心结构体Viper的一个属性,类型是func:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
type Viper struct {
    // Delimiter that separates a list of keys
    // used to access a nested value in one go
    keyDelim string
 
    // A set of paths to look for the config file in
    configPaths []string
 
    // The filesystem to read config from.
    fs afero.Fs
 
    // A set of remote providers to search for the configuration
    remoteProviders []*defaultRemoteProvider
 
    // Name of file to look for inside the path
    configName string
    configFile string
    configType string
    envPrefix string
 
    automaticEnvApplied bool
    envKeyReplacer   *strings.Replacer
 
    config     map[string]interface{}
    override    map[string]interface{}
    defaults    map[string]interface{}
    kvstore    map[string]interface{}
    pflags     map[string]FlagValue
    env      map[string]string
    aliases    map[string]string
    typeByDefValue bool
 
    // Store read properties on the object so that we can write back in order with comments.
    // This will only be used if the configuration read is a properties file.
    properties *properties.Properties
 
    onConfigChange func(fsnotify.Event)
}

它用来传入本次event来执行你写的函数。为什么修改会立即生效?相信第二个疑问已经得到解决了。

接下来看看OnConfigChange(func(e fsnotify.Event) {...... })的运行情况:

?
1
2
3
func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
    v.onConfigChange = run
}

方法参数为一个函数,类型为func(in fsnotify.Event)) {},这就意味着开发者需要把你自己的执行逻辑放到这个func里面,在监听到event时就会执行你写的函数,所以就可以这样写:

?
1
2
3
4
viperInstance.OnConfigChange(func(e fsnotify.Event) {
    log.Print("Config file updated.")
    viperLoadConf(viperInstance)  // viperLoadConf函数就是将最新配置注入到自定义结构体对象的逻辑
})

而OnConfigChange方法的参数会赋值给形参run并传到viper实例的onConfigChange属性,以WatchConfig()方法中的v.onConfigChange(event)来执行这个函数。

到此,第一个疑问也就解决了。

到此这篇关于详解go基于viper实现配置文件热更新及其源码分析的文章就介绍到这了,更多相关go viper文件热更新内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/HYZX_9987/article/details/103924392

延伸 · 阅读

精彩推荐
  • Golang深入浅析Go中三个点(...)用法

    深入浅析Go中三个点(...)用法

    这篇文章主要介绍了深入浅析Go中三个点(...)用法,需要的朋友可以参考下...

    踏雪无痕SS6472021-11-17
  • GolangGo语言基础单元测试与性能测试示例详解

    Go语言基础单元测试与性能测试示例详解

    这篇文章主要为大家介绍了Go语言基础单元测试与性能测试示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助祝大家多多进步...

    枫少文7812021-12-05
  • GolangGolang 语言极简类型转换库cast的使用详解

    Golang 语言极简类型转换库cast的使用详解

    本文我们通过 cast.ToString() 函数的使用,简单介绍了cast 的使用方法,除此之外,它还支持很多其他类型,在这没有多多介绍,对Golang 类型转换库 cast相关知...

    Golang语言开发栈6112021-12-02
  • Golanggo语言获取系统盘符的方法

    go语言获取系统盘符的方法

    这篇文章主要介绍了go语言获取系统盘符的方法,涉及Go语言调用winapi获取系统硬件信息的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    无尽海3862020-04-24
  • GolangGolang实现四种负载均衡的算法(随机,轮询等)

    Golang实现四种负载均衡的算法(随机,轮询等)

    本文介绍了示例介绍了Golang 负载均衡的四种实现,主要包括了随机,轮询,加权轮询负载,一致性hash,感兴趣的小伙伴们可以参考一下...

    Gundy_8442021-08-09
  • GolangGo语言range关键字循环时的坑

    Go语言range关键字循环时的坑

    今天小编就为大家分享一篇关于Go语言range关键字循环时的坑,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来...

    benben_20154202020-05-23
  • GolangGo语言实现自动填写古诗词实例代码

    Go语言实现自动填写古诗词实例代码

    这篇文章主要给大家介绍了关于Go语言实现自动填写古诗词的相关资料,这是最近在项目中遇到的一个需求,文中通过示例代码介绍的非常详细,需要的朋...

    FengY5862020-05-14
  • GolangGO语言字符串处理Strings包的函数使用示例讲解

    GO语言字符串处理Strings包的函数使用示例讲解

    这篇文章主要为大家介绍了GO语言字符串处理Strings包的函数使用示例讲解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加...

    Jeff的技术栈6882022-04-14