Golang 程序中实现优雅关闭 HTTP SERVER

栏目: Go · 发布时间: 7年前

内容简介:Golang 中实现一个 HTTP SERVER 异常的简单,利用标准库 net/http 的实现仅需数行代码即可,但是一个生产环境可用的 HTTP SERVER 还必须考虑更多的问题,其中如何实现优雅关闭 HTTP SERVER 是一个必须要处理的问题。这里所说的如果你对 Golang 中监听并处理信号不了解,建议先花三分钟浏览一下本专栏的另一篇关于信号处理的文章:

Golang 中实现一个 HTTP SERVER 异常的简单,利用标准库 net/http 的实现仅需数行代码即可,但是一个生产环境可用的 HTTP SERVER 还必须考虑更多的问题,其中如何实现优雅关闭 HTTP SERVER 是一个必须要处理的问题。这里所说的 优雅 即是指在 HTTP SERVER 里监听特定的信号,并在接收到信号时做出相应的处理。中文世界里也常用 平滑 一词代替,说的都是同一个意思。

如果你对 Golang 中监听并处理信号不了解,建议先花三分钟浏览一下本专栏的另一篇关于信号处理的文章:

Golang 程序中如何监听并处理信号?

Talk is cheap. Show me the code.
package main

import (
    "context"
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "sync"
    "syscall"
    "time"
)

const addr = ":9527"

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "just another http server...")
    })
    //使用默认路由创建 http server
    srv := http.Server{
        Addr:    addr,
        Handler: http.DefaultServeMux,
    }
    //使用WaitGroup同步Goroutine
    var wg sync.WaitGroup
    exit := make(chan os.Signal)
    //监听 Ctrl+C 信号
    signal.Notify(exit, syscall.SIGINT, syscall.SIGTERM)
    go func() {
        <-exit
        wg.Add(1)
        //使用context控制srv.Shutdown的超时时间
        ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
        defer cancel()
        err := srv.Shutdown(ctx)
        if err != nil {
            fmt.Println(err)
        }
        wg.Done()
    }()

    fmt.Println("listening at " + addr)
    err := srv.ListenAndServe()

    fmt.Println("waiting for the remaining connections to finish...")
    wg.Wait()
    if err != nil && err != http.ErrServerClosed {
        panic(err)
    }
    fmt.Println("gracefully shutdown the http server...")
}

以上所述就是小编给大家介绍的《Golang 程序中实现优雅关闭 HTTP SERVER》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms of the Intelligent Web

Algorithms of the Intelligent Web

Haralambos Marmanis、Dmitry Babenko / Manning Publications / 2009-7-8 / GBP 28.99

Web 2.0 applications provide a rich user experience, but the parts you can't see are just as important-and impressive. They use powerful techniques to process information intelligently and offer featu......一起来看看 《Algorithms of the Intelligent Web》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具