详解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 相关文章推荐
Go语言使用select{}阻塞main函数介绍
Apr 25 Golang
用golang如何替换某个文件中的字符串
Apr 25 Golang
golang import自定义包方式
Apr 29 Golang
go mod 安装依赖 unkown revision问题的解决方案
May 06 Golang
GoLang中生成UUID唯一标识的实现
May 08 Golang
go语言基础 seek光标位置os包的使用
May 09 Golang
Golang 语言控制并发 Goroutine的方法
Jun 30 Golang
golang 语言中错误处理机制
Aug 30 Golang
GO语言异常处理分析 err接口及defer延迟
Apr 14 Golang
Golang 实现 WebSockets 之创建 WebSockets
Apr 24 Golang
Go调用Rust方法及外部函数接口前置
Jun 14 Golang
GoFrame gredis缓存DoVar Conn连接对象 自动序列化GoFrame gredisDo/DoVar方法Conn连接对象自动序列化/反序列化总结
Jun 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读注册表
2006/10/09 PHP
php+ajax实时刷新简单实例
2015/02/25 PHP
php实现的简易扫雷游戏实例
2015/07/09 PHP
为你的 Laravel 验证器加上多验证场景的实现
2020/04/07 PHP
JavaScrip单线程引擎工作原理分析
2010/09/04 Javascript
javascript页面加载完执行事件代码
2014/02/11 Javascript
js 判断js函数、变量是否存在的简单示例代码
2014/03/04 Javascript
基于jquery实现等比缩放图片
2014/12/03 Javascript
举例详解JavaScript中Promise的使用
2015/06/24 Javascript
Vue.js实现实例搜索应用功能详细代码
2017/08/24 Javascript
Vue 兄弟组件通信的方法(不使用Vuex)
2017/10/26 Javascript
jquery学习笔记之无new构建详解
2017/12/07 jQuery
使用async、enterproxy控制并发数量的方法详解
2018/01/02 Javascript
Router解决跨模块下的页面跳转示例
2018/01/11 Javascript
JS实现处理时间,年月日,星期的公共方法示例
2019/05/31 Javascript
微信小程序实现张图片合成为一张并下载
2019/07/16 Javascript
JavaScript中继承原理与用法实例入门
2020/05/09 Javascript
基于react项目打包css引用路径错误解决方案
2020/10/28 Javascript
[02:53]DOTA2英雄基础教程 山岭巨人小小
2013/12/09 DOTA
Python3实现从文件中读取指定行的方法
2015/05/22 Python
Python功能键的读取方法
2015/05/28 Python
浅析Python编写函数装饰器
2016/03/18 Python
python获取指定字符串中重复模式最高的字符串方法
2018/06/29 Python
代码详解django中数据库设置
2019/01/28 Python
解决python运行启动报错问题
2020/06/01 Python
HTML5拖拽的简单实例
2016/05/30 HTML / CSS
跑步爱好者一站式服务网站:Jack Rabbit
2016/09/01 全球购物
巴西服装和鞋子购物网站:Marisa
2018/10/25 全球购物
Nordgreen美国官网:在线购买极简主义斯堪的纳维亚手表
2019/07/24 全球购物
房屋买卖委托公证书
2014/04/08 职场文书
党员活动日总结
2014/05/05 职场文书
三好学生先进事迹材料
2014/08/28 职场文书
电影焦裕禄观后感
2015/06/09 职场文书
初中思想品德教学反思
2016/02/24 职场文书
详解jQuery的核心函数和事件处理
2022/02/18 jQuery
关于Vue中的options选项
2022/03/22 Vue.js