Table of Contents
Elegant shutdown method
Implemented through semaphores
Through channel
Signals monitored by the program
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.
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.
Home Backend Development Golang Let's talk about the elegant shutdown method in golang

Let's talk about the elegant shutdown method in golang

Apr 27, 2023 am 09:11 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go language pack import: What is the difference between underscore and without underscore? Go language pack import: What is the difference between underscore and without underscore? Mar 03, 2025 pm 05:17 PM

This article explains Go's package import mechanisms: named imports (e.g., import &quot;fmt&quot;) and blank imports (e.g., import _ &quot;fmt&quot;). Named imports make package contents accessible, while blank imports only execute t

How to convert MySQL query result List into a custom structure slice in Go language? How to convert MySQL query result List into a custom structure slice in Go language? Mar 03, 2025 pm 05:18 PM

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

How to implement short-term information transfer between pages in the Beego framework? How to implement short-term information transfer between pages in the Beego framework? Mar 03, 2025 pm 05:22 PM

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

How can I define custom type constraints for generics in Go? How can I define custom type constraints for generics in Go? Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How do I write mock objects and stubs for testing in Go? How do I write mock objects and stubs for testing in Go? Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How to write files in Go language conveniently? How to write files in Go language conveniently? Mar 03, 2025 pm 05:15 PM

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How can I use tracing tools to understand the execution flow of my Go applications? How can I use tracing tools to understand the execution flow of my Go applications? Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

See all articles