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()
}
相关推荐
古城小栈14 小时前
Go实现的区块链 分片技术优化
golang·区块链·php
海上彼尚16 小时前
Go之路 - 2.go的常量变量[完整版]
开发语言·后端·golang
海上彼尚16 小时前
Go之路 - 1.gomod指令
开发语言·后端·golang
古城小栈17 小时前
Go语言原生智能合约开发与部署完全指南
golang·区块链·智能合约
小画家~17 小时前
第三十七:类型断言
开发语言·c++·算法·golang
wadesir18 小时前
Go语言常量与iota枚举详解(零基础掌握Go语言常量定义与iota枚举的使用)
开发语言·前端·golang
abcefg_h2 天前
Cookie,Session的介绍和如何保持TCP连接
网络·网络协议·tcp/ip·golang
卿雪2 天前
Redis 缓存问题:穿透、击穿、雪崩是什么及其解决方案
java·数据库·redis·sql·mysql·缓存·golang
小画家~2 天前
第三十七:定义错误类型
golang
Lovely Ruby2 天前
前端er Go-Frame 的学习笔记:实现 to-do 功能(四),确保开发和部署共用一套代码
前端·学习·golang