【问题标题】:golang http server graceful shutdown after a signalgolang http服务器在收到信号后优雅关闭
【发布时间】:2019-12-01 15:17:36
【问题描述】:

我正在尝试编写代码,以便在收到信号时优雅地关闭 http 服务器。

我的代码有两个 go 例程 - signalHandler()simpleServiceStarter() - 一个用于信号处理,另一个用于 http 服务器。收到信号后,处理程序应关闭 http 服务器 所以simpleServiceStarter()ListenAndServe() 中断。下面是我的代码。

package main

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

var (
    simpleHTTPServer      http.Server
    sigChan               chan os.Signal
    simpleServiceShutdown chan bool
)

func simpleServiceStarter() {
    mux := http.NewServeMux()
    simpleHTTPServer := &http.Server{
        Addr:           ":9000",
        Handler:        mux,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    fmt.Printf("\nstarting http server on :9000 ")
    err := simpleHTTPServer.ListenAndServe()
    if err != http.ErrServerClosed {
        fmt.Printf("error starting simple service or closing listener - %v\n", err)
    }
    fmt.Printf("simple service http server shutdown completed - %v\n", err)

    // communicate with main thread
    simpleServiceShutdown <- true
}

func signalHandler() {
    // Handle SIGINT and SIGHUP.
    signal.Notify(sigChan, syscall.SIGINT, syscall.SIGHUP)

    sig := <-sigChan
    fmt.Printf("\nsignalHandler() received signal: %v\n", sig)

    // gracefully shutdown http server
    err := simpleHTTPServer.Shutdown(context.Background())
    fmt.Printf("simple service shutdown on signal %v, error: %v\n", sig, err)
    close(sigChan)

}

func main() {
    // block all async signals to this server. And we register only SIGINT and SIGHUP for now.
    signal.Ignore()

    sigChan = make(chan os.Signal, 1)
    simpleServiceShutdown = make(chan bool)
    go signalHandler()

    go simpleServiceStarter()
    <-simpleServiceShutdown // wait server to shutdown
    close(simpleServiceShutdown)
}

发送信号后,服务器没有中断,还在等待。

Run the program as:
$ ./simpleHttp 

starting http server on :9000 
signalHandler() received signal: interrupt
simple service shutdown on signal interrupt, error: <nil>
$

From another terminal send the signal as:
tester 30202  4379  0 09:14 pts/8    00:00:00 ./simpleHttp
kill -s SIGINT 30202

我正在使用go1.12.6 linux/amd64

【问题讨论】:

    标签: go


    【解决方案1】:

    func simpleServiceStarter() 中声明本地 simpleHTTPServer := &amp;http.Server 哪个影子全局

    var (
        simpleHTTPServer      http.Server
    

    不能在func simpleServiceStarter() 范围之外引用此局部变量。只需在func simpleServiceStarter() 中输入simpleHTTPServer = &amp;http.Server(不带冒号)

    【讨论】:

      猜你喜欢
      • 2019-05-23
      • 2011-07-12
      • 2019-07-25
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      相关资源
      最近更新 更多