Go 里的超时控制也很简单

开发 后端
日常开发中我们大概率会遇到超时控制的场景,比如一个批量耗时任务、网络请求等;一个良好的超时控制可以有效的避免一些问题(比如 goroutine 泄露、资源不释放等)。

[[431857]]

前言

日常开发中我们大概率会遇到超时控制的场景,比如一个批量耗时任务、网络请求等;一个良好的超时控制可以有效的避免一些问题(比如 goroutine 泄露、资源不释放等)。

Timer

在 go 中实现超时控制的方法非常简单,首先第一种方案是 Time.After(d Duration):

  1. func main() { 
  2.  fmt.Println(time.Now()) 
  3.  x := <-time.After(3 * time.Second
  4.  fmt.Println(x) 

output:

  1. 2021-10-27 23:06:04.304596 +0800 CST m=+0.000085653 
  2. 2021-10-27 23:06:07.306311 +0800 CST m=+3.001711390 

time.After() 会返回一个 Channel,该 Channel 会在延时 d 段时间后写入数据。

有了这个特性就可以实现一些异步控制超时的场景:

  1. func main() { 
  2.  ch := make(chan struct{}, 1) 
  3.  go func() { 
  4.   fmt.Println("do something..."
  5.   time.Sleep(4*time.Second
  6.   ch<- struct{}{} 
  7.  }() 
  8.   
  9.  select { 
  10.  case <-ch: 
  11.   fmt.Println("done"
  12.  case <-time.After(3*time.Second): 
  13.   fmt.Println("timeout"
  14.  } 

这里假设有一个 goroutine 在跑一个耗时任务,利用 select 有一个 channel 获取到数据便退出的特性,当 goroutine 没有在有限时间内完成任务时,主 goroutine 便会退出,也就达到了超时的目的。

  1. do something... 
  2. timeout 

timer.After 取消,同时 Channel 发出消息,也可以关闭通道等通知方式。

注意 Channel 最好是有大小,防止阻塞 goroutine ,导致泄露。

Context

第二种方案是利用 context,go 的 context 功能强大;

利用 context.WithTimeout() 方法会返回一个具有超时功能的上下文。

  1. ch := make(chan string) 
  2. timeout, cancel := context.WithTimeout(context.Background(), 3*time.Second
  3. defer cancel() 
  4. go func() { 
  5.  time.Sleep(time.Second * 4) 
  6.  
  7.  ch <- "done" 
  8. }() 
  9.  
  10. select { 
  11. case res := <-ch: 
  12.  fmt.Println(res) 
  13. case <-timeout.Done(): 
  14.  fmt.Println("timout", timeout.Err()) 

同样的用法,context 的 Done() 函数会返回一个 channel,该 channel 会在当前工作完成或者是上下文取消生效。

  1. timout context deadline exceeded 

通过 timeout.Err() 也能知道当前 context 关闭的原因。

goroutine 传递 context

使用 context 还有一个好处是,可以利用其天然在多个 goroutine 中传递的特性,让所有传递了该 context 的 goroutine 同时接收到取消通知,这点在多 go 中应用非常广泛。

  1. func main() { 
  2.  total := 12 
  3.  var num int32 
  4.  log.Println("begin"
  5.  ctx, cancelFunc := context.WithTimeout(context.Background(), 3*time.Second
  6.  for i := 0; i < total; i++ { 
  7.   go func() { 
  8.    //time.Sleep(3 * time.Second
  9.    atomic.AddInt32(&num, 1) 
  10.    if atomic.LoadInt32(&num) == 10 { 
  11.     cancelFunc() 
  12.    } 
  13.   }() 
  14.  } 
  15.  for i := 0; i < 5; i++ { 
  16.   go func() { 
  17.  
  18.    select { 
  19.    case <-ctx.Done(): 
  20.     log.Println("ctx1 done", ctx.Err()) 
  21.    } 
  22.  
  23.    for i := 0; i < 2; i++ { 
  24.     go func() { 
  25.      select { 
  26.      case <-ctx.Done(): 
  27.       log.Println("ctx2 done", ctx.Err()) 
  28.      } 
  29.     }() 
  30.    } 
  31.  
  32.   }() 
  33.  } 
  34.  
  35.  time.Sleep(time.Second*5) 
  36.  log.Println("end", ctx.Err()) 
  37.  fmt.Printf("执行完毕 %v", num) 

在以上例子中,无论 goroutine 嵌套了多少层,都是可以在 context 取消时获得消息(当然前提是 context 得传递走)

某些特殊情况需要提前取消 context 时,也可以手动调用 cancelFunc() 函数。

Gin 中的案例

Gin 提供的 Shutdown(ctx) 函数也充分使用了 context。

  1. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second
  2. defer cancel() 
  3. if err := srv.Shutdown(ctx); err != nil { 
  4.  log.Fatal("Server Shutdown:", err) 
  5. log.Println("Server exiting"

比如以上代码便是超时等待 10s 进行 Gin 的资源释放,实现的原理也和上文的例子相同。

总结

因为写 go 的时间不长,所以自己写了一个练手的项目:一个接口压力测试工具。

其中一个很常见的需求就是压测 N 秒后退出,这里正好就应用到了相关知识点,同样是初学 go 的小伙伴可以参考。

 

https://github.com/crossoverJie/ptg/blob/d0781fcb5551281cf6d90a86b70130149e1525a6/duration.go#L41

 

责任编辑:武晓燕 来源: crossoverJie
相关推荐

2022-10-26 07:26:38

2023-11-08 08:43:08

calc函数CSS

2018-12-24 08:46:52

Kubernetes对象模型

2015-08-27 09:30:38

2010-09-28 15:48:30

2010-10-09 16:51:47

2018-12-05 10:26:43

服务器HFSIIS

2010-07-08 14:53:38

SQLServer实现

2010-06-12 10:10:55

2017-07-10 13:31:03

异构 存储

2010-07-19 08:36:56

SQL Server内

2010-07-13 15:56:16

SQL Server获

2010-06-09 13:55:24

设置MySQL同步

2010-05-19 16:45:26

MySQL自动启动

2009-06-11 16:44:06

超时控制Java线程

2017-07-14 08:18:08

异构存储复制

2010-09-29 14:48:16

2010-08-16 15:37:37

DB2 -964问题

2016-12-12 19:16:43

数据云端

2010-06-17 17:11:03

SQL Server
点赞
收藏

51CTO技术栈公众号