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 小时前
字节跳动Go后端开发工程师面试题精选:10道高频考题+答案解析
面试·golang·php·求职招聘
xxjj998a19 小时前
PHP vs Go vs Python:三大语言终极对比
python·golang·php
jieyucx19 小时前
Go 切片核心:子切片详解(下篇)
开发语言·算法·golang·切片
会编程的土豆1 天前
由c/c++速通go语言,新手必看
c语言·c++·golang
念何架构之路2 天前
Go Socket编程
开发语言·后端·golang
codeejun2 天前
每日一Go-59、云原生入门为什么一定要学Docker?
docker·云原生·golang
初心未改HD2 天前
gRPC 与 Protobuf 实战指南
开发语言·golang
jieyucx2 天前
Go语言切片:动态灵活的数据序列
算法·golang·指针·顺序表·数组·结构体·切片
初心未改HD2 天前
Go 文件与 I/O 操作完全指南
开发语言·golang
geovindu2 天前
go: Mediator Pattern
设计模式·golang·中介者模式