Home  >  Article  >  Backend Development  >  Worker and HTTP server shut down gracefully

Worker and HTTP server shut down gracefully

WBOY
WBOYforward
2024-02-15 14:48:071085browse

Worker 和 HTTP 服务器正常关闭

php editor Xigua introduces the normal shutdown of Worker and HTTP server in this article. During the development process, it is very important to shut down the Worker and HTTP server correctly to ensure the release of resources and the normal exit of the program. This article will explain in detail how to shut down Workers and HTTP servers correctly, as well as some common problems and solutions. Let's learn together how to ensure the normal shutdown of the server and improve the stability and reliability of the application.

Question content

I am trying to create a worker process and an http server that are started independently and listen for termination and exit gracefully when completed.

For some reason the worker thread starts but the http server doesn't start until the sigterm event is sent. The http server will start only after sending the sigterm event. What is the problem below?

Output

https://gosamples.dev is the best
https://gosamples.dev is the best
https://gosamples.dev is the best
^c2023/05/27 15:07:52 listening on http server port:

process finished with the exit code 0

Code

package main

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

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    go func() {
        signals := make(chan os.Signal, 1)
        signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
        <-signals

        cancel()
    }()

    var wg sync.WaitGroup

    wg.Add(1)
    go func() {
        if err := myWorker(ctx); err != nil {
            cancel()
        }
        wg.Done()
    }()

    wg.Add(1)
    go func() {
        if err := startServer(ctx); err != nil {
            cancel()
        }
        wg.Done()
    }()

    wg.Wait()
}

func myWorker(ctx context.Context) error {
    shouldStop := false

    go func() {
        <-ctx.Done()
        shouldStop = true
    }()

    for !shouldStop {
        fmt.Println("https://gosamples.dev is the best")
        time.Sleep(1 * time.Second)
    }

    return nil
}

func startServer(ctx context.Context) error {
    var srv http.Server

    go func() {
        <-ctx.Done() // Wait for the context to be done

        // Shutdown the server
        if err := srv.Shutdown(context.Background()); err != nil {
            // Error from closing listeners, or context timeout:
            log.Printf("HTTP server Shutdown: %v", err)
        }
    }()

    if err := srv.ListenAndServe(); err != http.ErrServerClosed {
        // Error starting or closing listener:
        return fmt.Errorf("HTTP server ListenAndServe: %w", err)
    }

    log.Printf("Listening on HTTP server port: %s", srv.Addr)

    http.HandleFunc("/readiness", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
    })
    http.HandleFunc("/liveness", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
    })

    return nil
}

Workaround

If I read your code correctly, you are starting the server before defining the route handler. This means that when the server starts, it doesn't know about your /readiness and /liveness endpoints because you haven't added them yet. As a result, the server starts, but it does nothing because it has no routes to process.

Then you don't define the addr field in the http.server instance. listenandserve() uses the address defined in the addr field of the http.server instance that calls it. If empty, it defaults to ":http", but this is not explicitly stated in your code and can lead to confusion.

I moved srv.listenandserve to the very end of startserver. What did I miss?

The problem is not where srv.listenandserve is in the function, but how http.server is configured and when the http handler is set.

In the original code, you set the http handler after the server starts. The handlers need to be set before starting the server because once the server is running it will not pick up any new handlers defined later.

And the log statement log.printf("listening on http server port: %s", srv.addr) is located after srv.listenandserve(), this is a blocking call . This means that the log statement will only be run after the server is stopped, which is why you can only see it after sending the sigterm signal.

Try reorganizing your startserver function like this:

func startServer(ctx context.Context) error {
    srv := &http.Server{
        Addr: ":8080", // Define the address where you want the server to listen
    }

    http.HandleFunc("/readiness", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
    })
    http.HandleFunc("/liveness", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
    })

    go func() {
        <-ctx.Done() // Wait for the context to be done

        // Shutdown the server
        if err := srv.Shutdown(context.Background()); err != nil {
            // Error from closing listeners, or context timeout:
            log.Printf("HTTP server Shutdown: %v", err)
        }
    }()

    log.Printf("Listening on HTTP server port: %s", srv.Addr)

    if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        // Error starting or closing listener:
        return fmt.Errorf("HTTP server ListenAndServe: %w", err)
    }

    return nil
}

In the modified version of the startserver function, the server now knows about your /readiness and /liveness endpoints because they were defined before the server started .
http handlers are set before the server starts, and log statements are printed before the server starts. This should resolve your issue and allow the server to start and handle requests as expected. Additionally, now the server knows where to listen because addr is clearly defined.

The above is the detailed content of Worker and HTTP server shut down gracefully. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete