gs

package module
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 7 Imported by: 5

README

English | 中文

logo

Go Report Card Build Status Go Reference

Introduction

Graceful Shutdown is a common requirement for most services. It is considered a best practice to gracefully shut down a service when it receives a termination signal. The process of graceful shutdown typically involves the following steps:

  1. Create a TerminateSignal instance and register the desired termination signal.
  2. Register the resources that need to be closed when the service is terminated.
  3. Use the WaitForAsync, WaitForSync, or WaitForForceSync method to wait for the TerminateSignal instance to gracefully shut down.

[!IMPORTANT]

It is strongly recommended to use the latest stable version of the library after v0.1.3. Previous versions have significant logic and control issues and are no longer recommended.

Advantages

  • Simple and user-friendly
  • No external dependencies required
  • Low memory footprint
  • Supports timeout signals
  • Supports context
  • Supports multiple signals

Installation

go get github.com/shengyanli1982/gs

Quick Start

GS is a simple and easy-to-use library for graceful shutdown. To use it, follow these steps:

  1. Create a TerminateSignal instance.
  2. Register the resources that need to be closed when the service is terminated.
  3. Use the appropriate waiting method (WaitForAsync, WaitForSync, or WaitForForceSync) to wait for the TerminateSignal instance to gracefully shut down.

[!IMPORTANT]

If you are using GS on Windows, make sure to use it with a console application.

Methods

Create

  • NewTerminateSignal: Create a new TerminateSignal instance.
  • NewTerminateSignalWithContext: Create a new TerminateSignal instance with context.

TerminateSignal

  • RegisterCancelHandles: Register the resources that need to be closed when the service is terminated.
  • GetStopContext: Get the context of the TerminateSignal instance.
  • Close: Close the TerminateSignal instance asynchronously.
  • SyncClose: Close the TerminateSignal instance synchronously.

Waiting

  • WaitForAsync: Wait for the TerminateSignal instance to gracefully shut down asynchronously.
  • WaitForSync: Wait for the TerminateSignal instance to gracefully shut down synchronously.
  • WaitForForceSync: Wait for the TerminateSignal instance to gracefully shut down strict synchronously.

[!NOTE]

Differences between synchronously (SyncClose) and strict synchronously (ForceSyncClose)

// SyncClose 表示同步关闭,即在不同的 TerminateSignal 中同步执行关闭操作, eg: t1.Close() then t2.Close() then t3.Close()
// 在每个 TerminateSignal 中,是异步执行的
// SyncClose represents synchronous closure, i.e., the closure operation is performed synchronously in different TerminateSignal, eg: t1.Close() then t2.Close() then t3.Close()
// In each TerminateSignal, it is asynchronous
SyncClose

// ForceSyncClose 表示强制同步关闭,即在不同的 TerminateSignal 中同步执行关闭操作, eg: t1.Close() then t2.Close() then t3.Close()
// 在每个 TerminateSignal 中,是完全同步执行的
// ForceSyncClose represents forced synchronous closure, i.e., the closure operation is performed synchronously in different TerminateSignal, eg: t1.Close() then t2.Close() then t3.Close()
// In each TerminateSignal, it is completely synchronous
ForceSyncClose

ForceSyncClose is completely synchronous, while SyncClose is asynchronous in each TerminateSignal.

[!IMPORTANT]

The WaitingForGracefulShutdown method is deprecated since v0.1.3. It is recommended to use the WaitForAsync, WaitForSync, or WaitForForceSync methods instead.

Example

[!TIP]

The os.Process.Signal() method only works on Linux and MacOS, and is invalid for Windows. If you want to test the code on Windows, please refer to the gracefull_windows_test.go code.

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/shengyanli1982/gs"
)

// 模拟一个服务
// Simulate a service
type testTerminateSignal struct{}

// Close 方法用于关闭 testTerminateSignal 服务
// The Close method is used to close the testTerminateSignal service
func (t *testTerminateSignal) Close() {
	fmt.Println("testTerminateSignal.Close()")
}

// 模拟一个服务
// Simulate a service
type testTerminateSignal2 struct{}

// Shutdown 方法用于关闭 testTerminateSignal2 服务
// The Shutdown method is used to close the testTerminateSignal2 service
func (t *testTerminateSignal2) Shutdown() {
	fmt.Println("testTerminateSignal2.Shutdown()")
}

// 模拟一个服务
// Simulate a service
type testTerminateSignal3 struct{}

// Terminate 方法用于关闭 testTerminateSignal3 服务
// The Terminate method is used to close the testTerminateSignal3 service
func (t *testTerminateSignal3) Terminate() {
	fmt.Println("testTerminateSignal3.Terminate()")
}

func main() {
	// 创建一个新的 TerminateSignal 实例
	// Create a new TerminateSignal instance
	s := gs.NewTerminateSignal()

	// 创建三个测试服务的实例
	// Create instances of three test services
	t1 := &testTerminateSignal{}
	t2 := &testTerminateSignal2{}
	t3 := &testTerminateSignal3{}

	// 注册需要在终止信号发生时执行的处理函数
	// Register the handle functions to be executed when the termination signal occurs
	s.RegisterCancelHandles(t1.Close, t2.Shutdown, t3.Terminate)

	// 在新的 goroutine 中执行一个函数
	// Execute a function in a new goroutine
	go func() {
		// 等待 2 秒
		// Wait for 2 seconds
		time.Sleep(2 * time.Second)

		// 查找当前进程
		// Find the current process
		p, err := os.FindProcess(os.Getpid())
		if err != nil {
			fmt.Println(err.Error())
		}

		// 向当前进程发送中断信号, os.Process.Signal() 对 Linux 和 MacOS 有效, Windows 无效
		// Send an interrupt signal to the current process, os.Process.Signal() is valid for Linux and MacOS, invalid for Windows
		err = p.Signal(os.Interrupt)
		if err != nil {
			fmt.Println(err.Error())
		}
	}()

	// 等待所有的异步关闭信号
	// Wait for all asynchronous shutdown signals
	gs.WaitForAsync(s)

	// 打印一条消息,表示服务已经优雅地关闭
	// Print a message indicating that the service has been gracefully shut down
	fmt.Println("shutdown gracefully")
}

Result

$ go run demo.go
testTerminateSignal3.Terminate()
testTerminateSignal.Close()
testTerminateSignal2.Shutdown()
shutdown gracefully

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WaitForAsync added in v0.1.3

func WaitForAsync(sigs ...*TerminateSignal)

WaitForAsync 函数等待所有的异步关闭信号 The WaitForAsync function waits for all asynchronous shutdown signals

func WaitForForceSync added in v0.1.3

func WaitForForceSync(sigs ...*TerminateSignal)

WaitForForceSync 函数等待所有的强制同步关闭信号 The WaitForForceSync function waits for all forced synchronous shutdown signals

func WaitForSync added in v0.1.3

func WaitForSync(sigs ...*TerminateSignal)

WaitForSync 函数等待所有的同步关闭信号 The WaitForSync function waits for all synchronous shutdown signals

func WaitingForGracefulShutdown deprecated

func WaitingForGracefulShutdown(sigs ...*TerminateSignal)

WaitingForGracefulShutdown 函数等待所有的关闭信号 The WaitingForGracefulShutdown function waits for all shutdown signals

Deprecated: As of GS v0.1.3 this function simply calls WaitForAsync.

Types

type CloseType added in v0.1.3

type CloseType int8

CloseType 是一个 int8 类型的别名,用于表示关闭类型 CloseType is an alias for int8, used to represent the type of closure

const (
	// ASyncClose 表示异步关闭,即在新的 goroutine 中执行关闭操作
	// ASyncClose represents asynchronous closure, i.e., the closure operation is performed in a new goroutine
	ASyncClose CloseType = iota

	// SyncClose 表示同步关闭,即在不同的 TerminateSignal 中同步执行关闭操作, eg: t1.Close() then t2.Close() then t3.Close()
	// 在每个 TerminateSignal 中,是异步执行的
	// SyncClose represents synchronous closure, i.e., the closure operation is performed synchronously in different TerminateSignal, eg: t1.Close() then t2.Close() then t3.Close()
	// In each TerminateSignal, it is asynchronous
	SyncClose

	// ForceSyncClose 表示强制同步关闭,即在不同的 TerminateSignal 中同步执行关闭操作, eg: t1.Close() then t2.Close() then t3.Close()
	// 在每个 TerminateSignal 中,是完全同步执行的
	// ForceSyncClose represents forced synchronous closure, i.e., the closure operation is performed synchronously in different TerminateSignal, eg: t1.Close() then t2.Close() then t3.Close()
	// In each TerminateSignal, it is completely synchronous
	ForceSyncClose
)

定义了三种关闭类型:异步关闭、同步关闭和强制同步关闭 Three types of closure are defined: asynchronous closure, synchronous closure, and forced synchronous closure

type TerminateSignal

type TerminateSignal struct {
	// contains filtered or unexported fields
}

TerminateSignal 结构体包含了一个 context,一个取消函数,一个等待组,一个函数切片和一个 sync.Once 实例 The TerminateSignal struct contains a context, a cancel function, a wait group, a function slice, and a sync.Once instance

func NewTerminateSignal

func NewTerminateSignal() *TerminateSignal

NewTerminateSignal 创建一个带有超时的 TerminateSignal 实例 NewTerminateSignal creates a TerminateSignal instance with a timeout

func NewTerminateSignalWithContext

func NewTerminateSignalWithContext(ctx context.Context) *TerminateSignal

NewTerminateSignalWithContext 创建一个带有上下文和超时的 TerminateSignal 实例 NewTerminateSignalWithContext creates a TerminateSignal instance with context and timeout

func (*TerminateSignal) Close

func (s *TerminateSignal) Close(wg *sync.WaitGroup)

Close 方法异步关闭 TerminateSignal 实例 The Close method asynchronously closes the TerminateSignal instance

func (*TerminateSignal) GetStopContext added in v0.1.1

func (s *TerminateSignal) GetStopContext() context.Context

GetStopContext 获取停止信号的 Context GetStopContext gets the Context of the stop signal

func (*TerminateSignal) RegisterCancelHandles added in v0.1.5

func (s *TerminateSignal) RegisterCancelHandles(handles ...func())

RegisterCancelHandles 注册需要取消的处理函数 RegisterCancelHandles registers the handle functions to be canceled

func (*TerminateSignal) SyncClose added in v0.1.3

func (s *TerminateSignal) SyncClose(wg *sync.WaitGroup)

SyncClose 方法同步关闭 TerminateSignal 实例 The SyncClose method synchronously closes the TerminateSignal instance

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL