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()
}
相关推荐
Tony Bai2 小时前
Go 在 Web3 的统治力:2025 年架构与生态综述
开发语言·后端·架构·golang·web3
q***06293 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
Wenhao.6 小时前
LeetCode Hot100 每日温度
数据结构·算法·leetcode·golang
未来之窗软件服务9 小时前
幽冥大陆(二十二)dark语言智慧农业电子秤读取——东方仙盟炼气期
开发语言·windows·golang·东方仙盟·东方仙盟sdk
Ryan ZX13 小时前
【Go语言基础】计算机基础知识
开发语言·后端·golang
q***71851 天前
【golang学习之旅】使用VScode安装配置Go开发环境
vscode·学习·golang
i***48611 天前
【漏洞复现】CVE-2019-11043(PHP远程代码执行漏洞)信息安全论文_含漏洞复现完整过程_含Linux环境go语言编译环境安装
linux·golang·php
q***78371 天前
【Golang】——Gin 框架中间件详解:从基础到实战
中间件·golang·gin
Ryan ZX1 天前
【Go语言基础】Go语言开发环境搭建
开发语言·后端·golang