当前位置:网站首页>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")
运行结果:

边栏推荐
猜你喜欢

深圳某游戏研发公司每个工位都装监控,网友:堪比“坐牢”!

PHP序列化:eval

IDEA找不到Database解决方法

Centos7 install mysql5.7 steps (graphical version)

系统集成项目管理工程师(软考中级)知识点总结【挣值分析】【关键路径】
![LRU缓存[线性表 -> 链表 -> hash定位 -> 双向链表]](/img/ad/dd80541514d6fedde8c730218fdf5a.png)
LRU缓存[线性表 -> 链表 -> hash定位 -> 双向链表]

PyQt5 rapid development and actual combat 10.2 compound interest calculation && 10.3 refresh blog clicks

IDEA版Postman插件Restful Fast Request,细节到位,功能好用

报错IDEA Terminated with exit code 1

SAP 电商云 Spartacus UI 和 Accelerator UI 里的 ASM 模块
随机推荐
基于姿态估计的护具佩戴检测与动作识别
Verilog——基于FPGA的贪吃蛇游戏(VGA显示)
SAP e-commerce cloud Spartacus SSR Optimization Engine execution sequence of several timeouts
matlab as(assert dominance)
golang八股文整理(持续搬运)
The cluster of safe mode
FastAPI 封装一个通用的response
2022年最新重庆建筑安全员模拟题库及答案
列表页优化思路
C#获得网卡信息 NetworkInterface IPInterfaceProperties
NameNode (NN) and SecondaryNameNode (2NN) working mechanism
FastAPI encapsulates a generic response
Wearing detection and action recognition of protective gear based on pose estimation
Comparison of ipv4 and ipv6 (IPV4)
NPM 使用介绍
Three-Phase PWM Rectifier Predictive Direct Power Control
全局平均池化层替代全连接层(最大池化和平均池化的区别)
IDEA连接MySQL数据库并执行SQL查询操作
SAP 电商云 Spartacus UI 和 Accelerator UI 里的 ASM 模块
跨境电商小知识之跨境电商物流定义以及方式讲解