详解Golang如何优雅的终止一个服务


Posted in Golang onMarch 21, 2022

前言

采用常规方式启动一个 Golang http 服务时,若服务被意外终止或中断,即未等待服务对现有请求连接处理并正常返回且亦未对服务停止前作一些必要的处理工作,这样即会造成服务硬终止。这种方式不是很优雅。

参看如下代码,该 http 服务请求路径为根路径,请求该路径,其会在 2s 后返回 hello。

var addr = flag.String("server addr", ":8080", "server address")

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(2 * time.Second)
        fmt.Fprintln(w, "hello")
    })
    http.ListenAndServe(*addr, nil)
}

若服务启动后,请求http://localhost:8080/,然后使用 Ctrl+C 立即中断服务,服务即会立即退出(exit status 2),请求未正常返回(ERR_CONNECTION_REFUSED),连接即马上断了。

接下来介绍使用 http.Server 的 Shutdown 方法结合 signal.Notify 来优雅的终止服务。

1 Shutdown 方法

Golang http.Server 结构体有一个终止服务的方法 Shutdown,其 go doc 如下。

func (srv *Server) Shutdown(ctx context.Context) error
    Shutdown gracefully shuts down the server without interrupting any active
    connections. Shutdown works by first closing all open listeners, then
    closing all idle connections, and then waiting indefinitely for connections
    to return to idle and then shut down. If the provided context expires before
    the shutdown is complete, Shutdown returns the context's error, otherwise it
    returns any error returned from closing the Server's underlying Listener(s).

    When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS
    immediately return ErrServerClosed. Make sure the program doesn't exit and
    waits instead for Shutdown to return.

    Shutdown does not attempt to close nor wait for hijacked connections such as
    WebSockets. The caller of Shutdown should separately notify such long-lived
    connections of shutdown and wait for them to close, if desired. See
    RegisterOnShutdown for a way to register shutdown notification functions.

    Once Shutdown has been called on a server, it may not be reused; future
    calls to methods such as Serve will return ErrServerClosed.

由文档可知:

使用 Shutdown 可以优雅的终止服务,其不会中断活跃连接。

其工作过程为:首先关闭所有开启的监听器,然后关闭所有闲置连接,最后等待活跃的连接均闲置了才终止服务。

若传入的 context 在服务完成终止前已超时,则 Shutdown 方法返回 context 的错误,否则返回任何由关闭服务监听器所引起的错误。

当 Shutdown 方法被调用时,Serve、ListenAndServe 及 ListenAndServeTLS 方法会立刻返回 ErrServerClosed 错误。请确保 Shutdown 未返回时,勿退出程序。

对诸如 WebSocket 等的长连接,Shutdown 不会尝试关闭也不会等待这些连接。若需要,需调用者分开额外处理(诸如通知诸长连接或等待它们关闭,使用 RegisterOnShutdown 注册终止通知函数)。

一旦对 server 调用了 Shutdown,其即不可再使用了(会报 ErrServerClosed 错误)。

有了 Shutdown 方法,我们知道在服务终止前,调用该方法即可等待活跃连接正常返回,然后优雅的关闭。

但服务启动后的某一时刻,程序如何知道服务被中断了呢?服务被中断时如何通知程序,然后调用 Shutdown 作处理呢?接下来看一下系统信号通知函数的作用。

2 signal.Notify 函数

signal 包的 Notify 函数提供系统信号通知的能力,其 go doc 如下。

func Notify(c chan<- os.Signal, sig ...os.Signal)
    Notify causes package signal to relay incoming signals to c. If no signals
    are provided, all incoming signals will be relayed to c. Otherwise, just the
    provided signals will.

    Package signal will not block sending to c: the caller must ensure that c
    has sufficient buffer space to keep up with the expected signal rate. For a
    channel used for notification of just one signal value, a buffer of size 1
    is sufficient.

    It is allowed to call Notify multiple times with the same channel: each call
    expands the set of signals sent to that channel. The only way to remove
    signals from the set is to call Stop.

    It is allowed to call Notify multiple times with different channels and the
    same signals: each channel receives copies of incoming signals
    independently.

由文档可知:

参数 c 是调用者的信号接收通道,Notify 可将进入的信号转到 c。sig 参数为需要转发的信号类型,若不指定,所有进入的信号都将会转到 c。

信号不会阻塞式的发给 c:调用者需确保 c 有足够的缓冲空间,以应对指定信号的高频发送。对于用于通知仅一个信号值的通道,缓冲大小为 1 即可。

同一个通道可以调用 Notify 多次:每个调用扩展了发送至该通道的信号集合。仅可调用 Stop 来从信号集合移除信号。

允许不同的通道使用同样的信号参数调用 Notify 多次:每个通道独立的接收进入信号的副本。

综上,有了 signal.Notify,传入一个 chan 并指定中断参数,这样当系统中断时,即可接收到信号。

参看如下代码,当使用 Ctrl+C 时,c 会接收到中断信号,程序会在打印“program interrupted”语句后退出。

func main() {
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt)
    <-c
    log.Fatal("program interrupted")
}
$ go run main.go

Ctrl+C

2019/06/11 17:59:11 program interrupted
exit status 1

3 Server 优雅的终止

接下来我们使用如上 signal.Notify 结合 http.Server 的 Shutdown 方法实现服务优雅的终止。

如下代码,Handler 与文章开始时的处理逻辑一样,其会在2s后返回 hello。

创建一个 http.Server 实例,指定端口与 Handler。

声明一个 processed chan,其用来保证服务优雅的终止后再退出主 goroutine。

新启一个 goroutine,其会监听 os.Interrupt 信号,一旦服务被中断即调用服务的 Shutdown 方法,确保活跃连接的正常返回(本代码使用的 Context 超时时间为 3s,大于服务 Handler 的处理时间,所以不会超时)。

处理完成后,关闭 processed 通道,最后主 goroutine 退出。

代码同时托管在 GitHub,欢迎关注(github.com/olzhy/go-excercises)。

var addr = flag.String("server addr", ":8080", "server address")

func main() {
    // handler
    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(2 * time.Second)
        fmt.Fprintln(w, "hello")
    })

    // server
    srv := http.Server{
        Addr:    *addr,
        Handler: handler,
    }

    // make sure idle connections returned
    processed := make(chan struct{})
    go func() {
        c := make(chan os.Signal, 1)
        signal.Notify(c, os.Interrupt)
        <-c

        ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
        defer cancel()
        if err := srv.Shutdown(ctx); nil != err {
            log.Fatalf("server shutdown failed, err: %v\n", err)
        }
        log.Println("server gracefully shutdown")

        close(processed)
    }()

    // serve
    err := srv.ListenAndServe()
    if http.ErrServerClosed != err {
        log.Fatalf("server not gracefully shutdown, err :%v\n", err)
    }

    // waiting for goroutine above processed
    <-processed
}

总结

到此这篇关于Golang如何优雅的终止一个服务的文章就介绍到这了,更多相关Golang终止服务内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Golang 相关文章推荐
Golang二维切片初始化的实现
Apr 08 Golang
Golang 空map和未初始化map的注意事项说明
Apr 29 Golang
golang slice元素去重操作
Apr 30 Golang
golang gopm get -g -v 无法获取第三方库的解决方案
May 05 Golang
如何利用golang运用mysql数据库
Mar 13 Golang
Golang jwt身份认证
Apr 20 Golang
Go获取两个时区的时间差
Apr 20 Golang
Golang入门之计时器
May 04 Golang
Go语言编译原理之源码调试
Aug 05 Golang
go goth封装第三方认证库示例详解
Aug 14 Golang
Go语言实现一个简单的并发聊天室的项目实战
Mar 18 #Golang
浅谈GO中的Channel以及死锁的造成
Mar 18 #Golang
Golang 并发下的问题定位及解决方案
Mar 16 #Golang
如何利用golang运用mysql数据库
深入理解go缓存库freecache的使用
Feb 15 #Golang
Go语言读取txt文档的操作方法
Jan 22 #Golang
一文搞懂Golang 时间和日期相关函数
You might like
php采用file_get_contents代替使用curl实例
2014/11/07 PHP
PHP操作路由器实现方法示例
2019/04/27 PHP
JQuery扩展插件Validate 3通过参数设置错误信息
2011/09/05 Javascript
使用PHP+JQuery+Ajax分页的实现
2013/04/23 Javascript
JQuery中$.ajax()方法参数详解及应用
2013/12/12 Javascript
JS基于Ajax实现的网页Loading效果代码
2015/10/27 Javascript
使用JavaScript获取URL中的参数(两种方法)
2016/11/16 Javascript
JavaScript中localStorage对象存储方式实例分析
2017/01/12 Javascript
JavaScript无操作后屏保功能的实现方法
2017/07/04 Javascript
angularjs实现过滤并替换关键字小功能
2017/09/19 Javascript
AngularJS实现的2048小游戏功能【附源码下载】
2018/01/03 Javascript
深入浅出理解JavaScript高级定时器原理与用法
2018/08/02 Javascript
jQuery.validate.js表单验证插件的使用代码详解
2018/10/22 jQuery
gulp构建小程序的方法步骤
2019/05/31 Javascript
JavaScript实现跟随鼠标移动的盒子
2021/01/28 Javascript
[41:52]2018DOTA2亚洲邀请赛3月29日小组赛B组Effect VS Secret
2018/03/30 DOTA
Python中optparse模块使用浅析
2015/01/01 Python
python检测远程udp端口是否打开的方法
2015/03/14 Python
分享python数据统计的一些小技巧
2016/07/21 Python
Python实现简单的四则运算计算器
2016/11/02 Python
Python连接数据库学习之DB-API详解
2017/02/07 Python
Django 添加静态文件的两种实现方法(必看篇)
2017/07/14 Python
python爬虫之验证码篇3-滑动验证码识别技术
2019/04/11 Python
Python matplotlib生成图片背景透明的示例代码
2019/08/30 Python
python3 使用traceback定位异常实例
2020/03/09 Python
scrapy与selenium结合爬取数据(爬取动态网站)的示例代码
2020/09/28 Python
KENZO官网:高田贤三在法国创立的品牌
2019/05/16 全球购物
澳大利亚设计师服装在线:MISHA
2019/10/07 全球购物
德国旅行、体验和活动的预订平台:Watado
2019/12/04 全球购物
银行职业规划书范文
2013/12/28 职场文书
问卷调查计划书
2014/01/10 职场文书
幼儿园三八妇女节活动方案
2014/03/11 职场文书
安全资料员岗位职责范本
2014/06/28 职场文书
出纳试用期自我鉴定范文
2014/09/16 职场文书
工作经验交流材料
2014/12/30 职场文书
导游带团欢迎词
2015/09/30 职场文书