Let's talk about the elegant shutdown method in golang

PHPz
Release: 2023-04-27 09:43:11
Original
1226 people have browsed it

When developing and using golang, you will generally encounter situations where you need to shut down or stop running. For example, if the program ends or an exception occurs, it needs to be shut down gracefully.

Graceful shutdown can stop the program and at the same time allow the started tasks to be processed, avoiding problems such as data loss and resource leakage, and not causing unnecessary losses to the client. This article discusses the graceful shutdown method of golang.

Elegant shutdown method

In golang, it is not difficult to implement graceful shutdown. We can do it by setting a semaphore or channel. The specific implementation method is as follows:

Implemented through semaphores

package main

import (
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    stop := make(chan os.Signal, 1)
    signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)

    log.Println("Starting...")

    go func() {
        <-stop
        log.Println("Stopping...")

        // 处理关闭逻辑
        time.Sleep(3 * time.Second)

        log.Println("Graceful shutdown finished")
        os.Exit(0)
    }()

    // 处理业务逻辑
    for {
        log.Println("Running...")
        time.Sleep(1 * time.Second)
    }
}
Copy after login

In this code, a signal buffer channel of type os.Signal and length 1 is created through make, and then the operating system is told through the Notify function in the signal package that we want to monitor The signals are SIGINT and SIGTERM, both of which can represent the program's shutdown request.

Next, we started a goroutine and listened to the stop channel. Once the SIGINT or SIGTERM signal is received, the execution of the goroutine will be triggered. During the execution process, we process the shutdown logic. Time.Sleep is used here to simulate a time-consuming operation to better test whether our program ends normally. Finally, the operating system is notified through the os.Exit function that the program shutdown request has been processed.

In the main goroutine, we process the business logic and print "Running..." every second. Here is just a simple example; usually, when we process the business logic, we need to save it regularly. data and release resources, etc.

Through channel

package main

import (
    "log"
    "os"
    "time"
)

func main() {
    done := make(chan bool)

    log.Println("Starting...")

    go func() {
        osSignals := make(chan os.Signal, 1)
        signal.Notify(osSignals, syscall.SIGINT, syscall.SIGTERM)

        select {
        case <-osSignals:
            log.Println("Stopping...")

            // 处理关闭逻辑
            time.Sleep(3 * time.Second)

            log.Println("Graceful shutdown finished")
            done <- true
        }
    }()

    // 处理业务逻辑
    for {
        log.Println("Running...")
        time.Sleep(1 * time.Second)
        select {
        case <-done:
            return // 正常退出
        default:
            continue
        }
    }
}
Copy after login

In this code, we create a done variable of bool type to indicate whether our program has been completed, and then process the business logic in the main goroutine and print it regularly. "Running..." and listen to done through the select function. If the done variable is set to true, the program ends and returns to the main function to complete the program exit.

In another goroutine, we create a signal buffer channel of type os.Signal and length 1 through make, and then tell the operating system through the Notify function in the signal package what signal we want to monitor. It's SIGINT and SIGTERM. Next, listen to osSignals through the select function. If a SIGINT or SIGTERM signal is received, a specific operation will be triggered.

Signals monitored by the program

In Linux systems, there are generally the following signals:

##SIGINTTerminal interrupt character, usually issued through Control CSIGTERM Termination signal, usually used to request the program to stop running on its own SIGHUP Suspend signal, usually indicates that a terminal connection has been interrupted and needs Re-read the configuration file, etc.SIGUSR1-31Custom signal##SIGKILLSIGSTOPSIGCONTSIGPIPESIGALRMSIGCHLDNormally, we only need to listen to the SIGINT and SIGTERM signals.
Signal name Signal description
Kill The dead process signal cannot be caught or ignored. The process can only be violently killed.
The stop process signal cannot be caught or ignored. The process can only be violently stopped.
Continue running the process
Pipe rupture signal, usually indicating reading data The other party has closed the connection
Alarm clock signal, used to trigger an operation regularly
Subprocess end signal

The role of graceful shutdown

Through graceful shutdown, we can avoid data loss, resource leakage and other problems caused by failed requests and operations. For long-running programs and Applications that provide services are especially important. Especially in distributed systems and microservice architectures, graceful shutdown can effectively ensure system stability and performance. If there is no targeted problem handling function, the program may end arbitrarily or trigger a crash after receiving a stop signal, causing serious problems. Causing confusion and even unnecessary losses to the client.

Summary

Through this article, we learned how to use golang's channel and os/signal packages for graceful shutdown, and how to complete graceful shutdown by listening to signals. In actual development, the normal shutdown of an application is a very important task. Graceful shutdown can effectively improve the stability of the program and avoid problems such as resource waste and data loss.

The above is the detailed content of Let's talk about the elegant shutdown method in golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!