实现很简单,直接上代码
package main
import (
"fmt"
"os"
"time"
"zx_alert/cmd/cmd"
"zx_alert/config"
logg "zx_alert/utils/log"
)
func main() {
go func() {
var lastFileStat os.FileInfo
for {
stat, err := os.Stat("./config.json")
if err != nil {
msg := fmt.Sprintf("获取文件状态失败,err:%s", err.Error())
logg.Logger.Error(msg)
time.Sleep(time.Second * 60)
continue
}
if lastFileStat == nil {
lastFileStat = stat
time.Sleep(time.Second * 60)
continue
}
if stat.ModTime() != lastFileStat.ModTime() {
logg.Logger.Info("配置发生变化,重载中...")
if err = config.LoadConf(); err != nil {
msg := fmt.Sprintf("热加载配置失败,err:%s", err.Error())
logg.Logger.Error(msg)
time.Sleep(time.Second * 60)
} else {
lastFileStat = stat
msg := fmt.Sprintf("配置重载ok, new config:【%v】", config.Conf)
logg.Logger.Info(msg)
}
}
time.Sleep(time.Second * 60)
}
}()
xxx
}
func LoadConf() error {
confByte, err := os.ReadFile("./config.json")
if err != nil {
return err
}
err = json.Unmarshal(confByte, &Conf)
if err != nil {
return err
}
return nil
}