Go語言利用time.After實現(xiàn)超時控制的方法詳解
前言
在開始之前,對time.After使用有疑問的朋友們可以看看這篇文章:http://www.dbjr.com.cn/article/146063.htm
我們在Golang網(wǎng)絡編程中,經(jīng)常要遇到設置超時的需求,本文就來給大家詳細介紹了Go語言利用time.After實現(xiàn)超時控制的相關內(nèi)容,下面話不多說了,來一起看看詳細的介紹吧。
場景:
假設業(yè)務中需調(diào)用服務接口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ù),就相當于實現(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è)務返回值。
select語句阻塞等待最先返回數(shù)據(jù)的channel,當先接收到time.After的通道數(shù)據(jù)時,select則會停止阻塞并執(zhí)行該case的代碼。此時就已經(jīng)實現(xiàn)了對業(yè)務代碼的超時處理。
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
Go?Error?嵌套實現(xiàn)創(chuàng)建方式
這篇文章主要介紹了Go?Error?嵌套到底是怎么實現(xiàn)的?大家都知道創(chuàng)建error有兩種方式分別是errors.new()另一種是fmt.errorf(),本文通過詳細例子給大家介紹,需要的朋友可以參考下2022-01-01
GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧
這篇文章主要為大家介紹了GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

