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()
}
相关推荐
hrhcode7 小时前
【java工程师快速上手go】二.Go进阶特性
java·golang·go
Tomhex9 小时前
Go字符串拼接最佳实践
golang·go
zs宝来了10 小时前
Go 内存管理:三色标记 GC 与逃逸分析
golang·go·后端技术
zs宝来了14 小时前
Go pprof 性能剖析:CPU、内存与锁分析
golang·go·后端技术
hrhcode15 小时前
【java工程师快速上手go】一.Go语言基础
java·开发语言·golang
LlNingyu16 小时前
Go 实现无锁环形队列:面向多生产者多消费者的高性能 MPMC 设计
开发语言·golang·队列·mpmc·数据通道
深挖派17 小时前
GoLand 2026.1 安装配置与环境搭建 (保姆级图文教程)
后端·golang·编辑器·go·goland
geovindu17 小时前
go: Factory Method Pattern
开发语言·后端·golang
zs宝来了18 小时前
Go Context:上下文传播与取消机制
golang·go·源码解析·后端技术
GDAL19 小时前
为什么选择gin?
golang·gin