服务和配置文件修改后经常需要重新启动是不是很麻烦,其实go服务热重启工具有很多,下面我就自己的使用心得以供交流
服务热重启工具之bee
bee 工具,我比较青睐bee(谁用谁知道),使用过beego框架的肯定不陌生,同样适用gin框架,要求项目的根目录必须有go.mod文件,在目录下
bee run启动项目,其他的操作可以自己在github上参考
# v1
go get github.com/beego/bee
# v2
go get github.com/beego/bee/v2
服务热重启工具之realize,这个github上的点赞数也比较多
go get github.com/oxequa/realize
配置文件监控
# 文件监控的第三方库
github.com/fsnotify/fsnotify
# 配置文件解读和监控
github.com/spf13/viper
gin使用案例
package main
import (
"fmt"
"net/http"
"github.com/fsnotify/fsnotify"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
type Config struct {
Port int `mapstructure:"port"`
Version string `mapstructure:"version"`
Log string `mapstructure:"log"`
}
var Conf = new(Config)
func main() {
viper.SetConfigFile("./conf/config.yaml") // 指定配置文件路径
err := viper.ReadInConfig() // 读取配置信息
if err != nil { // 读取配置信息失败
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
// 将读取的配置信息保存至全局变量Conf
if err := viper.Unmarshal(Conf); err != nil {
panic(fmt.Errorf("unmarshal conf failed, err:%s \n", err))
}
// 监控配置文件变化
viper.WatchConfig()
// 注意!!!配置文件发生变化后要同步到全局变量Conf
viper.OnConfigChange(func(in fsnotify.Event) {
fmt.Println("配置文件被人修改啦...")
if err := viper.Unmarshal(Conf); err != nil {
panic(fmt.Errorf("unmarshal conf failed, err:%s \n", err))
}
})
r := gin.Default()
// 访问/version的返回值会随配置文件的变化而变化
r.GET("/version", func(c *gin.Context) {
c.String(http.StatusOK, Conf.Version)
})
if err := r.Run(fmt.Sprintf(":%d", Conf.Port)); err != nil {
panic(err)
}
}
有兴趣的可以在里边加入优雅退出,
bee run启动服务,服务修改完保存后自动的重启,如果配置文件修改后也会被监控到,但是自身服务的端口在配置文件中修改后不会重启服务和修改端口,但是可以读取到,自己实现重启