Last active
June 7, 2022 02:10
-
-
Save flxxyz/2ef918da07b5367af040df685d40fc88 to your computer and use it in GitHub Desktop.
golang 热加载配置文件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// golang 热加载配置文件 | |
// golang config hot reload | |
package main | |
import ( | |
"encoding/json" | |
"io/ioutil" | |
"log" | |
"os" | |
"sync" | |
"time" | |
) | |
//配置结构体 | |
type Config struct { | |
Filename string | |
LastModifyTime int64 | |
Lock *sync.RWMutex | |
Data interface{} | |
} | |
func NewConfig(filename string, data interface{}) *Config { | |
conf := &Config{ | |
Filename: filename, | |
Data: data, | |
Lock: &sync.RWMutex{}, | |
} | |
conf.parse() | |
go conf.reload() | |
return conf | |
} | |
//解析函数 | |
func (c *Config) parse() bool { | |
//记录最后修改时间 | |
fileInfo, _ := os.Stat(c.Filename) | |
c.LastModifyTime = fileInfo.ModTime().Unix() | |
//读取文件内容 | |
file, err := ioutil.ReadFile(c.Filename) | |
if err != nil { | |
log.Println("读取配置文件失败:", err) | |
//直接退出程序 | |
os.Exit(1) | |
} | |
//解json | |
c.Lock.Lock() | |
if err = json.Unmarshal(file, &c.Data); err != nil { | |
log.Println("解析json出错:", err) | |
return false | |
} | |
log.Printf("文件内容 = %+v\n", c.Data) | |
return true | |
} | |
//重载函数 | |
func (c *Config) reload() { | |
ticker := time.NewTicker(time.Second * 5) | |
for _ = range ticker.C { | |
func() { | |
fileInfo, _ := os.Stat(c.Filename) | |
currModifyTime := fileInfo.ModTime().Unix() | |
if currModifyTime > c.LastModifyTime { | |
if c.parse() { | |
log.Println("重新加载配置文件conf.json") | |
} | |
c.Lock.Unlock() | |
} | |
}() | |
} | |
} | |
func main() { | |
//json配置文件结构体 | |
type Data struct { | |
Host string `json:"host"` | |
Port int `json:"port"` | |
Passwd string `json:"passwd"` | |
Db int `json:"db"` | |
} | |
_ = NewConfig("test_config.json", &Data{}) | |
select {} | |
//end := make(chan bool, 1) | |
//<-end | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"host": "127.0.0.1", | |
"port": 6379, | |
"passwd": "", | |
"db": 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment