前言
在開始之前,對time.After使用有疑問的朋友們可以看看這篇文章:https://www.jb51.net/article/146063.htm
我們在Golang網(wǎng)絡(luò)編程中,經(jīng)常要遇到設(shè)置超時的需求,本文就來給大家詳細介紹了Go語言利用time.After實現(xiàn)超時控制的相關(guān)內(nèi)容,下面話不多說了,來一起看看詳細的介紹吧。
場景:
假設(shè)業(yè)務(wù)中需調(diào)用服務(wù)接口A,要求超時時間為5秒,那么如何優(yōu)雅、簡潔的實現(xiàn)呢?
我們可以采用select+time.After的方式,十分簡單適用的實現(xiàn)。
首先,我們先看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類型的通道消息。那么,基于這個函數(shù),就相當(dāng)于實現(xiàn)了定時器,且是無阻塞的。
超時控制的代碼實現(xiàn):
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來接收協(xié)程里的業(yè)務(wù)返回值。
select語句阻塞等待最先返回數(shù)據(jù)的channel,當(dāng)先接收到time.After
的通道數(shù)據(jù)時,select則會停止阻塞并執(zhí)行該case的代碼。此時就已經(jīng)實現(xiàn)了對業(yè)務(wù)代碼的超時處理。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
您可能感興趣的文章:- 詳解Golang 中的并發(fā)限制與超時控制
- 一文搞懂如何實現(xiàn)Go 超時控制