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()
}
相关推荐
源代码•宸2 小时前
简版抖音项目——项目需求、项目整体设计、Gin 框架使用、视频模块方案设计、用户与鉴权模块方案设计、JWT
经验分享·后端·golang·音视频·gin·jwt·gorm
nix.gnehc3 小时前
深入浅出 Go 内存管理(二):预分配、GC 与内存复用实战
golang
creator_Li3 小时前
Golang的Channel
golang·channel
nix.gnehc4 小时前
深入理解Go并发核心:GMP模型与Goroutine底层原理
开发语言·算法·golang
nix.gnehc5 小时前
深入浅出 Go 内存管理(一):三级缓存、逃逸分析与内存碎片
golang
nix.gnehc5 小时前
Go进阶攻坚+专家深耕级学习清单|聚焦高并发、高性能中间件/底层框架开发(Java开发者专属)
学习·中间件·golang
普通网友20 小时前
PL/SQL语言的正则表达式
开发语言·后端·golang
一个处女座的程序猿O(∩_∩)O1 天前
Go语言Map值不可寻址深度解析:原理、影响与解决方案
开发语言·后端·golang
呆萌很1 天前
Go语言常用基本数据类型快速入门
golang