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()
}
相关推荐
百***48074 小时前
【Golang】slice切片
开发语言·算法·golang
q***92514 小时前
Windows上安装Go并配置环境变量(图文步骤)
开发语言·windows·golang
稚辉君.MCA_P8_Java15 小时前
通义 Go 语言实现的插入排序(Insertion Sort)
数据结构·后端·算法·架构·golang
源代码•宸15 小时前
GoLang写一个简单版生命游戏模拟器
经验分享·笔记·学习·游戏·golang
q***017715 小时前
Linux 下安装 Golang环境
linux·运维·golang
稚辉君.MCA_P8_Java15 小时前
Gemini永久会员 Go 实现动态规划
数据结构·后端·算法·golang·动态规划
柠石榴18 小时前
go-1 模型
开发语言·后端·golang
想搞艺术的程序员1 天前
深入 NSQ 延迟消息实现原理:设计巧思与性能优化
性能优化·golang·nsq
(づど)2 天前
解决VSCode中安装Go环境Gopls失败的问题
vscode·golang
wavemap2 天前
先到先得:免费订阅一年ChatGPT Go会员
开发语言·chatgpt·golang