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()
}
相关推荐
XMYX-010 小时前
17 - Go 通道 Channel 底层原理 + 实战详解
开发语言·golang
Tomhex18 小时前
Go调用C代码的场景与实践
golang
黑牛儿19 小时前
Swoole协程 vs Go协程:PHP开发者一看就懂的实战对比
后端·golang·php·swoole
Wenweno0o1 天前
Eino-Document 组件使用指南
golang·大模型·智能体·eino
lolo大魔王1 天前
Go语言的反射机制
开发语言·后端·算法·golang
XMYX-01 天前
16 - Go 协程(goroutine):从基础到实战
开发语言·golang
lolo大魔王1 天前
Go语言的文件处理操作
golang
jieyucx1 天前
Golang 完整安装与 VSCode 开发环境搭建教程
开发语言·vscode·golang
codeejun2 天前
每日一Go-52、Go微服务--请求超时与熔断策略实战
微服务·golang·iphone
codeejun2 天前
每日一Go-53、Go微服务--限流与降级
开发语言·微服务·golang