自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Go 里的超時(shí)控制也很簡單

開發(fā) 后端
日常開發(fā)中我們大概率會遇到超時(shí)控制的場景,比如一個(gè)批量耗時(shí)任務(wù)、網(wǎng)絡(luò)請求等;一個(gè)良好的超時(shí)控制可以有效的避免一些問題(比如 goroutine 泄露、資源不釋放等)。

[[431857]]

前言

日常開發(fā)中我們大概率會遇到超時(shí)控制的場景,比如一個(gè)批量耗時(shí)任務(wù)、網(wǎng)絡(luò)請求等;一個(gè)良好的超時(shí)控制可以有效的避免一些問題(比如 goroutine 泄露、資源不釋放等)。

Timer

在 go 中實(shí)現(xiàn)超時(shí)控制的方法非常簡單,首先第一種方案是 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() 會返回一個(gè) Channel,該 Channel 會在延時(shí) d 段時(shí)間后寫入數(shù)據(jù)。

有了這個(gè)特性就可以實(shí)現(xiàn)一些異步控制超時(shí)的場景:

  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.  } 

這里假設(shè)有一個(gè) goroutine 在跑一個(gè)耗時(shí)任務(wù),利用 select 有一個(gè) channel 獲取到數(shù)據(jù)便退出的特性,當(dāng) goroutine 沒有在有限時(shí)間內(nèi)完成任務(wù)時(shí),主 goroutine 便會退出,也就達(dá)到了超時(shí)的目的。

  1. do something... 
  2. timeout 

timer.After 取消,同時(shí) Channel 發(fā)出消息,也可以關(guān)閉通道等通知方式。

注意 Channel 最好是有大小,防止阻塞 goroutine ,導(dǎo)致泄露。

Context

第二種方案是利用 context,go 的 context 功能強(qiáng)大;

利用 context.WithTimeout() 方法會返回一個(gè)具有超時(shí)功能的上下文。

  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() 函數(shù)會返回一個(gè) channel,該 channel 會在當(dāng)前工作完成或者是上下文取消生效。

  1. timout context deadline exceeded 

通過 timeout.Err() 也能知道當(dāng)前 context 關(guān)閉的原因。

goroutine 傳遞 context

使用 context 還有一個(gè)好處是,可以利用其天然在多個(gè) goroutine 中傳遞的特性,讓所有傳遞了該 context 的 goroutine 同時(shí)接收到取消通知,這點(diǎn)在多 go 中應(yīng)用非常廣泛。

  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("執(zhí)行完畢 %v", num) 

在以上例子中,無論 goroutine 嵌套了多少層,都是可以在 context 取消時(shí)獲得消息(當(dāng)然前提是 context 得傳遞走)

某些特殊情況需要提前取消 context 時(shí),也可以手動(dòng)調(diào)用 cancelFunc() 函數(shù)。

Gin 中的案例

Gin 提供的 Shutdown(ctx) 函數(shù)也充分使用了 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"

比如以上代碼便是超時(shí)等待 10s 進(jìn)行 Gin 的資源釋放,實(shí)現(xiàn)的原理也和上文的例子相同。

總結(jié)

因?yàn)閷?go 的時(shí)間不長,所以自己寫了一個(gè)練手的項(xiàng)目:一個(gè)接口壓力測試工具。

其中一個(gè)很常見的需求就是壓測 N 秒后退出,這里正好就應(yīng)用到了相關(guān)知識點(diǎn),同樣是初學(xué) go 的小伙伴可以參考。

 

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

 

責(zé)任編輯:武曉燕 來源: crossoverJie
相關(guān)推薦

2022-10-26 07:26:38

2018-12-24 08:46:52

Kubernetes對象模型

2023-11-08 08:43:08

calc函數(shù)CSS

2015-08-27 09:30:38

2010-09-28 15:48:30

2010-06-12 10:10:55

2010-10-09 16:51:47

2010-07-08 14:53:38

SQLServer實(shí)現(xiàn)

2018-12-05 10:26:43

服務(wù)器HFSIIS

2024-09-06 10:05:47

SpELSpring權(quán)限

2017-07-14 08:18:08

異構(gòu)存儲復(fù)制

2010-09-29 14:48:16

2017-07-10 13:31:03

異構(gòu) 存儲

2010-07-19 08:36:56

SQL Server內(nèi)

2010-07-13 15:56:16

SQL Server獲

2010-06-09 13:55:24

設(shè)置MySQL同步

2010-05-19 16:45:26

MySQL自動(dòng)啟動(dòng)

2024-07-11 08:42:57

2010-06-17 17:11:03

SQL Server

2010-08-16 15:37:37

DB2 -964問題
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號