Web Services 优雅的关闭酒店

e1xvtsh3  于 2023-02-19  发布在  其他
关注(0)|答案(1)|浏览(172)

我正在尝试在我的一个服务器中添加优雅关闭。我知道代码是工作的。我希望在重新部署服务器后,首先优雅关闭工作,然后服务器将重新启动。但它没有发生。你们能告诉我可能的原因吗?

done := make(chan bool, 1)
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
    signal.Notify(quit, syscall.SIGHUP, syscall.SIGQUIT)
    signal.Notify(quit, syscall.SIGILL, syscall.SIGTRAP)
    signal.Notify(quit, syscall.SIGABRT, syscall.SIGBUS, syscall.SIGFPE)
    go func() {
        BootUpLog("before  <-quit")
        syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
        <-quit
        BootUpLog("shutting down")
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        server.SetKeepAlivesEnabled(false)
        if err := server.Shutdown(ctx); err != nil {
            BootUpLog(fmt.Sprintf("Error in graceful shutdown of the server: %v", err))
        }
        close(done)
    }()
    if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        BootUpLog(fmt.Sprintf("shut down with error: %v", err))
    }
    <-done
    BootUpLog("Shutdown gracefully.")
}

这里的日志“before〈-quit”正在打印,而在redeploymet之后,它在〈-quit通道中没有接收到任何信号。

wj8zmpe1

wj8zmpe11#

您的BootUpLog()实现是否存在问题?以下代码对我有效(main.go):

package main

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

func main() {
    fmt.Println("starting up")

    quit := make(chan os.Signal, 1)
    signal.Notify(quit, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
    signal.Notify(quit, syscall.SIGHUP, syscall.SIGQUIT)
    signal.Notify(quit, syscall.SIGILL, syscall.SIGTRAP)
    signal.Notify(quit, syscall.SIGABRT, syscall.SIGBUS, syscall.SIGFPE)

    server := &http.Server{
        Addr: ":8080",
    }
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    })
    down := make(chan struct{})

    go func() {
        defer close(down)
        err := server.ListenAndServe()
        fmt.Println("shutting down: ", err)
    }()

    go func() {
        fmt.Println("before <- quit")
        syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
        fmt.Println("after signal sent")
        <-quit
        fmt.Println("after signal received")
        server.Shutdown(context.Background())
    }()

    <-down
}

运行它:

$ go run main.go
starting up
before <- quit
after signal sent
after signal received
shutting down:  http: Server closed

相关问题