golang服务优雅的退出

参考goframe框架,重要的以下几个信号量.

// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.

// +build !windows

package ghttp

import (
	"context"
	"github.com/gogf/gf/internal/intlog"
	"os"
	"os/signal"
	"syscall"
)

// procSignalChan is the channel for listening the signal.
var procSignalChan = make(chan os.Signal)

// handleProcessSignal handles all signal from system.
func handleProcessSignal() {
	var sig os.Signal
	signal.Notify(
		procSignalChan,
		syscall.SIGINT,
		syscall.SIGQUIT,
		syscall.SIGKILL,
		syscall.SIGTERM,
		syscall.SIGABRT,
		syscall.SIGUSR1,
		syscall.SIGUSR2,
	)
	for {
		sig = <-procSignalChan
		intlog.Printf(context.TODO(), `signal received: %s`, sig.String())
		switch sig {
		// Shutdown the servers.
		case syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGABRT:
			shutdownWebServers(sig.String())
			return

		// Shutdown the servers gracefully.
		// Especially from K8S when running server in POD.
		case syscall.SIGTERM:
			shutdownWebServersGracefully(sig.String())
			return

		// Restart the servers.
		case syscall.SIGUSR1:
			if err := restartWebServers(sig.String()); err != nil {
				intlog.Error(context.TODO(), err)
			}
			return

		default:
		}
	}
}
posted @   jiftle  阅读(342)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
历史上的今天:
2017-09-19 javascript中实现sleep函数
2017-09-19 C#中基本类型占用字节数
2017-09-19 java中基本类型占用字节数
2017-09-19 c#序列化和反序列化list
点击右上角即可分享
微信分享提示