一文搞懂如何实现 Go 超时控制
为什么需要超时控制?
- 请求时间过长,用户侧可能已经离开本页面了,服务端还在消耗资源处理,得到的结果没有意义
- 过长时间的服务端处理会占用过多资源,导致并发能力下降,甚至出现不可用事故
Go 超时控制必要性
Go 正常都是用来写后端服务的,一般一个请求是由多个串行或并行的子任务来完成的,每个子任务可能是另外的内部请求,那么当这个请求超时的时候,我们就需要快速返回,释放占用的资源,比如goroutine,文件描述符等。
服务端常见的超时控制
- 进程内的逻辑处理
- 读写客户端请求,比如HTTP或者RPC请求
- 调用其它服务端请求,包括调用RPC或者访问DB等
没有超时控制会怎样?
为了简化本文,我们以一个请求函数 hardWork
为例,用来做啥的不重要,顾名思义,可能处理起来比较慢。
func hardWork(job interface{}) error {
time.Sleep(time.Minute)
return nil
}
func requestWork(ctx context.Context, job interface{}) error {
return hardWork(job)
}
这时客户端看到的就一直是大家熟悉的画面
绝大部分用户都不会看一分钟菊花,早早弃你而去,空留了整个调用链路上一堆资源的占用,本文不究其它细节,只聚焦超时实现。
下面我们看看该怎么来实现超时,其中会有哪些坑。
第一版实现
大家可以先不往下看,自己试着想想该怎么实现这个函数的超时,第一次尝试:
func requestWork(ctx context.Context, job interface{}) error {
ctx, cancel := context.WithTimeout(ctx, time.Second*2)
defer cancel()
done := make(chan error)
go func() {
done <- hardWork(job)
}()
select {
case err := <-done:
return err
case <-ctx.Done():
return ctx.Err()
}
}
我们写个 main 函数测试一下
func main() {
const total = 1000
var wg sync.WaitGroup
wg.Add(total)
now := time.Now()
for i := 0; i < total; i++ {
go func() {
defer wg.Done()
requestWork(context.Background(), "any")
}()
}
wg.Wait()
fmt.Println("elapsed:", time.Since(now))
}
跑一下试试效果
➜ go run timeout.go
elapsed: 2.005725931s
超时已经生效。但这样就搞定了吗?
goroutine 泄露
让我们在main函数末尾加一行代码看看执行完有多少goroutine
time.Sleep(time.Minute*2)
fmt.Println("number of goroutines:", runtime.NumGoroutine())
sleep 2分钟是为了等待所有任务结束,然后我们打印一下当前goroutine数量。让我们执行一下看看结果
➜ go run timeout.go
elapsed: 2.005725931s
number of goroutines: 1001
goroutine泄露了,让我们看看为啥会这样呢?首先,requestWork
函数在2秒钟超时后就退出了,一旦 requestWork
函数退出,那么 done channel
就没有goroutine接收了,等到执行 done <- hardWork(job)
这行代码的时候就会一直卡着写不进去,导致每个超时的请求都会一直占用掉一个goroutine,这是一个很大的bug,等到资源耗尽的时候整个服务就失去响应了。
那么怎么fix呢?其实也很简单,只要 make chan
的时候把 buffer size
设为1,如下:
done := make(chan error, 1)
这样就可以让 done <- hardWork(job)
不管在是否超时都能写入而不卡住goroutine。此时可能有人会问如果这时写入一个已经没goroutine接收的channel会不会有问题,在Go里面channel不像我们常见的文件描述符一样,不是必须关闭的,只是个对象而已,close(channel)
只是用来告诉接收者没有东西要写了,没有其它用途。
改完这一行代码我们再测试一遍:
➜ go run timeout.go
elapsed: 2.005655146s
number of goroutines: 1
goroutine泄露问题解决了!
panic 无法捕获
让我们把 hardWork
函数实现改成
panic("oops")
修改 main
函数加上捕获异常的代码如下:
go func() {
defer func() {
if p := recover(); p != nil {
fmt.Println("oops, panic")
}
}()
defer wg.Done()
requestWork(context.Background(), "any")
}()
此时执行一下就会发现panic是无法被捕获的,原因是因为在 requestWork
内部起的goroutine里产生的panic其它goroutine无法捕获。
解决方法是在 requestWork
里加上 panicChan
来处理,同样,需要 panicChan
的 buffer size
为1,如下:
func requestWork(ctx context.Context, job interface{}) error {
ctx, cancel := context.WithTimeout(ctx, time.Second*2)
defer cancel()
done := make(chan error, 1)
panicChan := make(chan interface{}, 1)
go func() {
defer func() {
if p := recover(); p != nil {
panicChan <- p
}
}()
done <- hardWork(job)
}()
select {
case err := <-done:
return err
case p := <-panicChan:
panic(p)
case <-ctx.Done():
return ctx.Err()
}
}
改完就可以在 requestWork
的调用方处理 panic
了。
超时时长一定对吗?
上面的 requestWork
实现忽略了传入的 ctx
参数,如果 ctx
已有超时设置,我们一定要关注此传入的超时是不是小于这里给的2秒,如果小于,就需要用传入的超时,go-zero/core/contextx
已经提供了方法帮我们一行代码搞定,只需修改如下:
ctx, cancel := contextx.ShrinkDeadline(ctx, time.Second*2)
Data race
这里 requestWork
只是返回了一个 error
参数,如果需要返回多个参数,那么我们就需要注意 data race
,此时可以通过锁来解决,具体实现参考 go-zero/zrpc/internal/serverinterceptors/timeoutinterceptor.go
,这里不做赘述。
完整示例
package main
import (
"context"
"fmt"
"runtime"
"sync"
"time"
"github.com/tal-tech/go-zero/core/contextx"
)
func hardWork(job interface{}) error {
time.Sleep(time.Second * 10)
return nil
}
func requestWork(ctx context.Context, job interface{}) error {
ctx, cancel := contextx.ShrinkDeadline(ctx, time.Second*2)
defer cancel()
done := make(chan error, 1)
panicChan := make(chan interface{}, 1)
go func() {
defer func() {
if p := recover(); p != nil {
panicChan <- p
}
}()
done <- hardWork(job)
}()
select {
case err := <-done:
return err
case p := <-panicChan:
panic(p)
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
const total = 10
var wg sync.WaitGroup
wg.Add(total)
now := time.Now()
for i := 0; i < total; i++ {
go func() {
defer func() {
if p := recover(); p != nil {
fmt.Println("oops, panic")
}
}()
defer wg.Done()
requestWork(context.Background(), "any")
}()
}
wg.Wait()
fmt.Println("elapsed:", time.Since(now))
time.Sleep(time.Second * 20)
fmt.Println("number of goroutines:", runtime.NumGoroutine())
}
更多细节
请参考 go-zero
源码:
go-zero/core/fx/timeout.go
go-zero/zrpc/internal/clientinterceptors/timeoutinterceptor.go
go-zero/zrpc/internal/serverinterceptors/timeoutinterceptor.go
项目地址
https://github.com/tal-tech/go-zero
欢迎使用 go-zero
并 star 支持我们!
微信交流
关注『微服务实践』公众号并回复 进群 获取社区群二维码。
一文搞懂如何实现 Go 超时控制的更多相关文章
- 一文搞懂RAM、ROM、SDRAM、DRAM、DDR、flash等存储介质
一文搞懂RAM.ROM.SDRAM.DRAM.DDR.flash等存储介质 存储介质基本分类:ROM和RAM RAM:随机访问存储器(Random Access Memory),易失性.是与CPU直接 ...
- 基础篇|一文搞懂RNN(循环神经网络)
基础篇|一文搞懂RNN(循环神经网络) https://mp.weixin.qq.com/s/va1gmavl2ZESgnM7biORQg 神经网络基础 神经网络可以当做是能够拟合任意函数的黑盒子,只 ...
- 一文搞懂 Prometheus 的直方图
原文链接:一文搞懂 Prometheus 的直方图 Prometheus 中提供了四种指标类型(参考:Prometheus 的指标类型),其中直方图(Histogram)和摘要(Summary)是最复 ...
- Web端即时通讯基础知识补课:一文搞懂跨域的所有问题!
本文原作者: Wizey,作者博客:http://wenshixin.gitee.io,即时通讯网收录时有改动,感谢原作者的无私分享. 1.引言 典型的Web端即时通讯技术应用场景,主要有以下两种形式 ...
- 一文搞懂vim复制粘贴
转载自本人独立博客https://liushiming.cn/2020/01/18/copy-and-paste-in-vim/ 概述 复制粘贴是文本编辑最常用的功能,但是在vim中复制粘贴还是有点麻 ...
- 三文搞懂学会Docker容器技术(中)
接着上面一篇:三文搞懂学会Docker容器技术(上) 6,Docker容器 6.1 创建并启动容器 docker run [OPTIONS] IMAGE [COMMAND] [ARG...] --na ...
- 三文搞懂学会Docker容器技术(下)
接着上面一篇:三文搞懂学会Docker容器技术(上) 三文搞懂学会Docker容器技术(中) 7,Docker容器目录挂载 7.1 简介 容器目录挂载: 我们可以在创建容器的时候,将宿主机的目录与容器 ...
- 一文搞懂所有Java集合面试题
Java集合 刚刚经历过秋招,看了大量的面经,顺便将常见的Java集合常考知识点总结了一下,并根据被问到的频率大致做了一个标注.一颗星表示知识点需要了解,被问到的频率不高,面试时起码能说个差不多.两颗 ...
- 一文搞懂 js 中的各种 for 循环的不同之处
一文搞懂 js 中的各种 for 循环的不同之处 See the Pen for...in vs for...of by xgqfrms (@xgqfrms) on CodePen. for &quo ...
随机推荐
- vue watcher errors
vue watcher errors Error in callback for watcher TypeError: Cannot set property of undefined" n ...
- memcached php
What is Memcached? Free & open source, high-performance, distributed memory object caching syste ...
- how to enable vue cli auto open the localhost url
how to enable vue cli auto open the localhost URL bad you must click the link by manually, waste of ...
- Programming Interview Questions Websites All In One
Programming Interview Questions Websites All In One 编程面试刷题网站 http://highscalability.com/ https://tri ...
- vue & table with operation slot
vue & table with operation slot seed demo <!-- @format --> <template> <seed ref=& ...
- js 检测浏览器开发者控制台是否被打开
var element = new Image(); Object.defineProperty(element, "id", { get: function () { debug ...
- django学习-6.模板templates
1.前言 首先,我们要知道html是一门静态语言,里面没法传一些动态参数,也就是一个写死的html页面. 那么,如果我们想实现在一个html页面里传入不同的参数对应的参数值,这就可以用django框架 ...
- window.onresize绑定事件以及解绑事件
问题描述 在Vue工程中,添加样式,部分需要做到自适应,需要添加resize事件,由于是单页面应用,如果组件初始化的时候绑定事件,在切换页面的时候不去注销事件,如果来回切换,会让resize事件执行多 ...
- idea中Maven-build lifecycle中下面标签详解
原文链接:https://blog.csdn.net/mr_orange_klj/article/details/82153945 Maven是基于一个build lifecycle的中心概念,意味着 ...
- Go的指针
目录 指针 一.指针的声明 二.指针的默认值(Zero Value) 三.指针的解引用 四.向函数传递指针参数 1.非 数组/切片 指针传参 2.数组/切片 指针传参 五.Go不支持指针运算 指针 指 ...