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()
}
相关推荐
止语Lab4 小时前
Go并发编程实战:Channel 还是 Mutex?一个场景驱动的选择框架
开发语言·后端·golang
王码码20356 小时前
Go语言的包管理:从GOPATH到Go Modules
后端·golang·go·接口
白毛大侠11 小时前
Docker vs 虚拟机 vs Go 用户态/内核态:这三组概念
运维·docker·golang·kvm
咬_咬11 小时前
go语言学习(map)
开发语言·学习·golang·map
U盘失踪了12 小时前
go 常量
开发语言·后端·golang
techdashen12 小时前
Go 的新垃圾回收器 Green Tea:一个降低GC CPU开销的大工程
开发语言·后端·golang
止语Lab12 小时前
Go 错误分层实战:从裸奔到三层防线
开发语言·golang
U盘失踪了16 小时前
go 切片
golang
ん贤16 小时前
口述Map
开发语言·面试·golang
XMYX-018 小时前
12 - Go Slice:底层原理、扩容机制与常见坑位
开发语言·golang