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()
}
相关推荐
zhangfeng11334 小时前
Ollama 支持模型微调但是不支持词库,支持RAG,go语言开发的大模型的推理应用,
人工智能·深度学习·golang
Dr.Kun6 小时前
【鲲码园PsychoPy】Go/No-go范式
开发语言·后端·golang
源代码•宸7 小时前
Golang面试题库(Interface、GMP)
开发语言·经验分享·后端·面试·golang·gmp·调度过程
西京刀客7 小时前
Go 语言中的 toolchain 指令-toolchain go1.23.6的作用和目的
开发语言·后端·golang·toolchain
暴躁小师兄数据学院8 小时前
【WEB3.0零基础转行笔记】编程语言篇-第一讲:Go语言基础及环节搭建
笔记·golang·web3·区块链
lead520lyq20 小时前
Golang本地内存缓存
开发语言·缓存·golang
小邓吖21 小时前
自己做了一个工具网站
前端·分布式·后端·中间件·架构·golang
金庆1 天前
Commit Hash from debug.ReadBuildInfo()
golang
源代码•宸1 天前
Golang面试题库(sync.Map)
开发语言·后端·面试·golang·map·sync.map·expunged
终生成长者1 天前
Golang cursorrule
开发语言·后端·golang