go优雅重启或停止
Go 重启 优雅 停止
2023-09-14 09:12:21 时间
想要优雅地重启或停止你的Web服务器,使用下面的方法
我们可以使用fvbock/endless来替换默认的ListenAndServe
,有关详细信息,请参阅问题#296
router := gin.Default()
router.GET("/", handler)
// [...]
endless.ListenAndServe(":4242", router)
一个替换方案
- manners:一个Go HTTP服务器,能优雅的关闭
- graceful:Graceful是一个go的包,支持优雅地关闭http.Handler服务器
- grace:对Go服务器进行优雅的重启和零停机部署
如果你的Go版本是1.8,你可能不需要使用这个库,考虑使用http.Server内置的Shutdown()方法进行优雅关闭,查看例子
// +build go1.8
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
time.Sleep(5 * time.Second)
c.String(http.StatusOK, "Welcome Gin Server")
})
srv := &http.Server{
Addr: ":8080",
Handler: router,
}
go func() {
// service connections
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}
相关文章
- 彩虹女神跃长空,Go语言进阶之Go语言高性能Web框架Iris项目实战-项目结构优化EP05
- Go基础语法之import原理(六)
- Go-Excelize API源码阅读(二十七)——SetRowOutlineLevel、SetColOutlineLevel
- go-cqhttp 群消息发送失败: 账号可能被风控的几种解决方法
- K8s源码分析(20)-client go组件之request和result
- 2022-10-28:以下go语言代码输出什么?A:false false;B:true false;C:true true;D
- GoLang15 - Go语言范围(Range)
- hash 表在 go 语言中的实现
- 「Go工具箱」强烈推荐:一个能让http请求回放的工具
- 「Go工具箱」一个对语义化版本进行解析、比较的库:go-version
- 「Go工具箱」redis官网推荐的go版本的分布式锁:redsync
- 「Go工具箱」一个简单、易用的多错误管理包:go-multierror
- GO语言开篇-Go语言急速入门(基础知识点)| 青训营笔记
- 基于Go/Grpc/kubernetes/Istio开发微服务的最佳实践尝试 - 1/3
- Go-包管理-go build(二)
- Go语言go mod包依赖管理工具使用详解
- go test命令(Go语言测试命令)完全攻略
- Go语言使用通道响应计时器的事件
- 精通Go语言开发Redis应用(go语言redis开发)
- 2016 年 Go 语言使用习惯调查
- 关键字在SQL Server中利用GO关键字实现更优化的操作(sqlserver中go)
- 便捷使用Go编程连接Redis(go连接redis)
- 使用Go语言实现Redis数据库(用go实现redis)
- 请求简单而快速用Go编写的Redis请求测试(用go写的redis)
- 数据库探索Go语言与Oracle数据库的结合(go语言中的oracle)
- Go语言操作Oracle数据库技术实践(go操作oracle)
- 语句使用Oracle中的Go语句来简化编程(oracle中go)
- GO语言常用的文件读取方式