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()
}
相关推荐
福大大架构师每日一题1 小时前
2026-01-15:下一个特殊回文数。用go语言,给定一个整数 n,求出一个比 n 更大的最小整数,该整数需要满足两条规则: 1. 它的十进制表示从左到右与从右到左完全一致(即读起来是对称的)。 2
python·算法·golang
Aerkui1 小时前
Go 泛型(Generics)详解
开发语言·后端·golang
clive.li1 小时前
go-webmvc框架推荐
开发语言·后端·golang
有代理ip2 小时前
常见数据采集问题及实操解决方案
爬虫·网络协议·http·golang·ssl
2501_941982058 小时前
马年 Go 篇:高并发企微机器人开发实战
开发语言·golang·企业微信
Mr -老鬼9 小时前
基于 Go 的脚本平台 APP 云控系统
开发语言·后端·golang
大鹏说大话9 小时前
深入理解 Go 中的 make(chan chan error):高阶通道的典型用法与实战场景
开发语言·后端·golang
Maguyusi1 天前
go 批量生成c++和lua proto文件
c++·golang·lua·protobuf
天空属于哈夫克31 天前
Go 开发:企微外部群主动发送消息
开发语言·golang·企业微信