select实现超时保护机制

1、使用channel优雅地关闭服务

go 复制代码
package main

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

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		return
	}
	_, _ = fmt.Fprintf(w, "测试", "")
}

func initRouters() {
	http.HandleFunc("/", IndexHandler)
}

func main() {
	initRouters()

	srv := http.Server{
		Addr: ":8081",
	}

	go func() {
		err := srv.ListenAndServe()
		if err != nil {
			return
		}
	}()

	// 优雅地关闭go服务
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit // 阻塞
	// 定时关闭
	ctx, cancle := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancle()
	if err := srv.Shutdown(ctx); err != nil {
		fmt.Println("Shutdown err:", err)
	}
	fmt.Println("Shutdown")
}

2、使用channel实现超时保护机制

go 复制代码
package main

import (
	"fmt"
	"time"
)

// select 可以优雅的处理超时
// 我限制我这个程序运行不可以超过1秒
func timeouting() {
	timeout := time.After(1 * time.Second) // 如果其它程序运行时间超过1s,那么出发保护机制 <-timeout 的操作
	ch := make(chan bool)

	go func() {
		time.Sleep(time.Second * 2)
		ch <- true
	}()

	select {
	case <-ch:
		fmt.Println("程序在1秒内启动")
	case <-timeout:
		fmt.Println("程序启动超时,请重新启动")
	}
}

func main() {
	timeouting()
}
相关推荐
ttwuai25 分钟前
Go后台管理系统开源项目有哪些?如何按交付形态筛掉不合适的仓库
开发语言·golang·开源
报错小能手1 小时前
GO面试题 Go基础面试题
golang
皓月盈江2 小时前
Go读写TXT文件
开发语言·后端·golang·go·读写txt文件·bufio·go读写txt
JavaPub-rodert3 小时前
开源一套 Go + React 后台管理系统,支持 RBAC 权限管理、Docker 一键部署!
react.js·golang·开源
FfHUCisI3 小时前
pprof 火焰图(Flame Graph)阅读与热点代码重构实战
架构·golang
JWASX18 小时前
Java 转 go 学习 - kitex(5)
学习·golang
谢亮_vipxieliang19 小时前
Go net/http 标准库深入——构建生产级 HTTP 服务
http·golang·iphone
小小龙学IT20 小时前
Go 语言 gRPC(grpc-go)深度解析
rpc·架构·golang·go
microrain1 天前
KNX 现场没有寄存器表:SagooIoT 楼宇驱动插件的组地址、DPT 与隧道
物联网·golang·开源·sagooiot
Duang007_1 天前
生产可观测性:从“系统慢“到“根因“的完整链路(Go / TypeScript)
后端·python·golang·typescript·prometheus