当前位置:网站首页>golang-gin-优雅重启
golang-gin-优雅重启
2022-07-31 13:01:00 【SakuraKizuna】
当gin框架部署以及运行的时候,如果瞬间重启或关闭,可能会造成其中的进程或者函数执行不完整,形成脏数据,导致系统个别功能运行异常。因此优雅的重启以及关闭是非常有必要的
原理:关闭http server后延迟几秒关闭系统,待各个函数运行完毕
此为https的请求,调用ListenAndServeTLS并且加入证书位置来开启tls。
如果为http则只需改为ListenAndServe即可
代码设置在main.go函数
//开启的端口号
//err = r.RunTLS(config.TLSConfig.Addr, config.TLSConfig.CertFile, config.TLSConfig.KeyFile)
//if err != nil {
// panic(err)
//}
srv := &http.Server{
Addr: config.TLSConfig.Addr,
Handler: r,
}
go func() {
// 基于https的服务连接开启
if err := srv.ListenAndServeTLS(config.TLSConfig.CertFile, config.TLSConfig.KeyFile) ; err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 3 seconds.
quit := make(chan os.Signal)
// kill (no param) default send syscanll.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println(time.Now().Format("2006-01-02 15:04:05")+"Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
// catching ctx.Done(). timeout of 3 seconds.
select {
case <-ctx.Done():
log.Println("timeout of 3 seconds.")
}
log.Println(time.Now().Format("2006-01-02 15:04:05")+" Server Done")
fmt.Println(time.Now().Format("2006-01-02 15:04:05")+" Server Done")
运行结果:

边栏推荐
猜你喜欢

Invalid bound statement (not found)出现的原因和解决方法

PHP序列化:eval

C#使用ComboBox控件

How does the SAP ABAP OData service support the $filter (filter) operation trial version

Centos7 install mysql5.7 steps (graphical version)

电商rpa是什么意思?跟电商rpi是一个意思吗?

Error EPERM operation not permitted, mkdir ‘Dsoftwarenodejsnode_cache_cacach两种解决办法

Exploring Plain Vision Transformer Backbones for Object Detection Paper Reading Notes

centos7安装mysql5.7

基于verilog的CRC校验(汇总)
随机推荐
SAP e-commerce cloud Spartacus SSR Optimization Engine execution sequence of several timeouts
WPF中报错:“未将对象引用设置到对象的实例。”
C#控件 ToolStripProgressBar 用法
集群中增加数据节点与退役数据节点
Optimization of five data submission methods
基本语法(一)
基于高阶微分器的无模型滑模控制器及其在自动电压调节器中的应用
JSP response对象简介说明
[RPI]树莓派监控温度及报警关机保护「建议收藏」
Flutter keyboard visibility
C#获得网卡信息 NetworkInterface IPInterfaceProperties
Structural controllability of switched linear systems with symmetry constraints
Talk about the message display mechanism on the SAP product UI
Error EPERM operation not permitted, mkdir ‘Dsoftwarenodejsnode_cache_cacach两种解决办法
小试牛刀—猜数字游戏
关于MySQL主从复制的数据同步延迟问题
PAT exam summary (exam experience)
硬盘分区,拓展C盘,不重装系统,不重装D盘软件的全教程。
PyQt5快速开发与实战 10.1 获取城市天气预报
AMBA APB学习记录(AMBA 2.0)