场景:假设业务中需调用服务接口A,要求超时时间为5秒,那么如何优雅、简洁的实现呢?golang
咱们能够采用
select
+time.After
的方式,十分简单适用的实现。函数
首先,咱们先看time.After()
源码:post
// 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
类型的通道消息。那么,基于这个函数,就至关于实现了定时器,且是无阻塞的。ui
超时控制的代码实现:.net
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
来接收协程里的业务返回值。code
select
语句阻塞等待最早返回数据的channel
,当先接收到time.After
的通道数据时,select
则会中止阻塞并执行该case
的代码。此时就已经实现了对业务代码的超时处理。协程
原文地址: https://shockerli.net/post/go...