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