前2两篇文章,通过定时器,信号,实现了配置文件热更新
接下来介绍第三种方式,通过内核fanotify,监听事件变化,来重新加载配置文件
fanotify.go
代码如下
packagemainimport ( "encoding/json""fmt""io/ioutil""log""time""github.com/fsnotify/fsnotify") //全局自定义拦截varintercept []Intercept//文件时间varftint64varfilenamestring="intercept.json"typeInterceptstruct { Urlstring`json:"url"`Methodstring`json:"method"`RespHeadermap[string]string`json:"resp_header"`RespBodyinterface{} `json:"resp_body"`RespCodeint`json:"resp_code"`} //读取自定义响应文件funcRead_resp() { intercept_data, err :=ioutil.ReadFile(filename) iferr!=nil { log.Fatalln(err) } err=json.Unmarshal(intercept_data, &intercept) iferr!=nil { log.Fatalln(err) } } funclisten(w*fsnotify.Watcher) { err :=w.Add(filename) iferr!=nil { log.Fatal(err) } } funcmain() { //初始读取Read_resp() watcher, err :=fsnotify.NewWatcher() iferr!=nil { log.Fatal(err) } deferwatcher.Close() listen(watcher) gofunc() { for { select { caseevent, ok :=<-watcher.Events: if!ok { return } log.Println("event:", event) ifevent.Op&fsnotify.Write==fsnotify.Write { log.Println("modified file:", event.Name) Read_resp() } ifevent.Op&fsnotify.Rename==fsnotify.Rename { listen(watcher) Read_resp() } caseerr, ok :=<-watcher.Errors: if!ok { return } log.Println("error:", err) } } }() //循环打印for { time.Sleep(1*time.Second) iflen(intercept) >0 { fmt.Println(intercept[0].RespBody) } } }
配置文件 intercept.json
[{ "url": "http://testing-ft2x-api.cloudcare.cn/api/v1/workspace/member/list", "method": "get", "resp_body": {"msg": "ehhjjj"}, "resp_header": {"Content-Type": "application/json"}, "resp_code": 200}]
运行程序
./fsnotify
然后更改配置文件
[{ "url": "http://testing-ft2x-api.cloudcare.cn/api/v1/workspace/member/list", "method": "get", "resp_body": {"msg": "ehhjjjjjjggg"}, "resp_header": {"Content-Type": "application/json"}, "resp_code": 200}]
程序输出
map[msg:ehh] map[msg:ehh] map[msg:ehh] 2021/11/13 09:45:22 event: "intercept.json": CHMOD 2021/11/13 09:45:22 event: "intercept.json": WRITE 2021/11/13 09:45:22 modified file: intercept.json map[msg:ehhjjj] map[msg:ehhjjj] map[msg:ehhjjj] map[msg:ehhjjj] map[msg:ehhjjj] map[msg:ehhjjj] 2021/11/13 09:45:29 event: "intercept.json": CHMOD 2021/11/13 09:45:29 event: "intercept.json": WRITE 2021/11/13 09:45:29 modified file: intercept.json map[msg:ehhjjjjjj] 2021/11/13 09:45:30 event: "intercept.json": CHMOD 2021/11/13 09:45:30 event: "intercept.json": WRITE 2021/11/13 09:45:30 modified file: intercept.json map[msg:ehhjjjjjjggg] map[msg:ehhjjjjjjggg] map[msg:ehhjjjjjjggg]