場景:
假設業務中需調用服務接口A,要求逾時時間為5秒,那麼如何優雅、簡潔的實作呢?
我們可以采用
+
select
的方式,十分簡單适用的實作。
time.After
首先,我們先看
time.After()
源碼:
// After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern, use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) <-chan Time {
return NewTimer(d).C
}
time.After()
表示
time.Duration
長的時候後傳回一條
time.Time
類型的通道消息。那麼,基于這個函數,就相當于實作了定時器,且是無阻塞的。
逾時控制的代碼實作:
package main
import (
"time"
"fmt"
)
func main() {
ch := make(chan string)
go func() {
time.Sleep(time.Second * 2)
ch <- "result"
}()
select {
case res := <-ch:
fmt.Println(res)
case <-time.After(time.Second * 1):
fmt.Println("timeout")
}
}
我們使用
channel
來接收協程裡的業務傳回值。
select
語句阻塞等待最先傳回資料的
channel
,當先接收到
time.After
的通道資料時,
select
則會停止阻塞并執行該
case
的代碼。此時就已經實作了對業務代碼的逾時處理。
原文位址: https://shockerli.net/post/golang-select-time-implement-timeout/