1. 程式人生 > 實用技巧 >無鎖載入配置

無鎖載入配置

動態載入配置,是服務中常用的功能。

動態載入配置是指不重啟服務情況下,使配置檔案的改動或者其他方式的改動生效。

一般普遍使用的方式是,加鎖方式。
其步驟大體過程如下:

  • 從配置檔案中讀取配置到新的配置變數
  • 加鎖
  • 將新的配置變數賦值給已有的配置變數
  • 解鎖
  • 使用新的配置

接下里,介紹一種方式,即無鎖載入配置。

golang中的atomic 提供了大量底層同步原語。

其中的Value就是本文的重點。

下面是載入配置的例子:

package main

import (
    "log"
    "sync/atomic"
    "time"
)

type Config struct {
    FileName string
    Addr string
    Port int
}

func main(){
    var configValue atomic.Value
    
    c := loadConfig()
    configValue.Store(c)

    newConfig := configValue.Load()
    log.Println("new config:", newConfig)
}

func loadConfig() *Config{
    log.Println("load config start...")
    // 重新讀取檔案配置
    config := & Config{
        FileName: "orange",
        Addr: "123456.com",
        Port: 12306,
    }
    
    time.Sleep(time.Second)
    
    log.Println("load config end...")
    return config
}

因為Store()Load()都是原子性操作,即使多個Store()或者多個Load()同時執行都不會有問題。

參考

atomic Value