激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

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

延伸 · 閱讀

精彩推薦
  • Golanggo語言制作端口掃描器

    go語言制作端口掃描器

    本文給大家分享的是使用go語言編寫的TCP端口掃描器,可以選擇IP范圍,掃描的端口,以及多線程,有需要的小伙伴可以參考下。 ...

    腳本之家3642020-04-25
  • GolangGolang通脈之數據類型詳情

    Golang通脈之數據類型詳情

    這篇文章主要介紹了Golang通脈之數據類型,在編程語言中標識符就是定義的具有某種意義的詞,比如變量名、常量名、函數名等等,Go語言中標識符允許由...

    4272021-11-24
  • Golanggolang的httpserver優雅重啟方法詳解

    golang的httpserver優雅重啟方法詳解

    這篇文章主要給大家介紹了關于golang的httpserver優雅重啟的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,...

    helight2992020-05-14
  • Golanggolang 通過ssh代理連接mysql的操作

    golang 通過ssh代理連接mysql的操作

    這篇文章主要介紹了golang 通過ssh代理連接mysql的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    a165861639710342021-03-08
  • Golanggolang json.Marshal 特殊html字符被轉義的解決方法

    golang json.Marshal 特殊html字符被轉義的解決方法

    今天小編就為大家分享一篇golang json.Marshal 特殊html字符被轉義的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧 ...

    李浩的life12792020-05-27
  • Golanggo日志系統logrus顯示文件和行號的操作

    go日志系統logrus顯示文件和行號的操作

    這篇文章主要介紹了go日志系統logrus顯示文件和行號的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    SmallQinYan12302021-02-02
  • GolangGolang中Bit數組的實現方式

    Golang中Bit數組的實現方式

    這篇文章主要介紹了Golang中Bit數組的實現方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧...

    天易獨尊11682021-06-09
  • Golanggolang如何使用struct的tag屬性的詳細介紹

    golang如何使用struct的tag屬性的詳細介紹

    這篇文章主要介紹了golang如何使用struct的tag屬性的詳細介紹,從例子說起,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看...

    Go語言中文網11352020-05-21
主站蜘蛛池模板: 亚洲第一成网站 | a视频在线看 | 一区二区久久电影 | 欧美日韩亚洲精品一区二区三区 | 久久精品一区二区三区国产主播 | 成人免费在线播放 | 蜜桃视频观看麻豆 | 最新日本中文字幕在线观看 | 久久久久国产成人免费精品免费 | 黄色影院在线看 | 成年片在线观看 | 美女毛片在线观看 | 在线成人一区 | 国产日产精品一区四区介绍 | 久久久久九九九女人毛片 | 免费色片 | 免费视频www在线观看 | 欧美高清一级片 | 妇子乱av一区二区三区 | 亚洲精品久久久久久 | 在线亚洲观看 | 激情小说区| 久久精品视频日本 | 特级黄毛片| 免费福利在线视频 | 最新一区二区三区 | 日本看片一区二区三区高清 | 99999久久久久久 | lutube成人福利在线观看污 | 狠狠干伊人网 | 91 在线视频观看 | 圆产精品久久久久久久久久久 | 国产精品嘿咻嘿咻在线播放 | 久久精品国产99国产精品澳门 | 国产亚洲精品久久久久久网站 | 自拍亚洲伦理 | 久草在线手机观看 | av免播放| 日韩美香港a一级毛片免费 日韩激情 | 中文字幕视频在线播放 | 亚洲情av|