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()
}
相关推荐
祁许11 小时前
【Golang】GORM - GEN工具 快速开始
开发语言·golang
showyoui11 小时前
深入Go语言之slice:不只是动态数组
后端·golang·slice·切片
余厌厌厌11 小时前
Go迭代器完全指南:从基础到实战
开发语言·golang
C墨羽15 小时前
使用Gin框架构建高并发教练预约微服务:架构设计与实战解析
微服务·架构·golang·gin
亚洲第一中锋_哈达迪2 天前
详解缓存淘汰策略:LFU
后端·缓存·golang
nextera-void2 天前
深入浅出 Golang:一次精神之旅
开发语言·golang·go
胡萝卜的兔2 天前
golang -gorm 增删改查操作,事务操作
开发语言·后端·golang
Go Dgg2 天前
【Go + Gin 实现「双 Token」管理员登录】
开发语言·golang·gin
nbsaas-boot2 天前
Go语言生态成熟度分析:为何Go还无法像Java那样实现注解式框架?
java·开发语言·golang
亚马逊云开发者2 天前
将 Go 应用从 x86 平台迁移至 Amazon Graviton:场景剖析与最佳实践
linux·数据库·golang