来源:自学PHP网 时间:2019-08-07 16:47 作者:小飞侠 阅读:次
[导读] Go语言利用time.After实现超时控制的方法详解...
|
前言 在开始之前,对time.After使用有疑问的朋友们可以看看这篇文章:https://www.jb51.net/article/146063.htm 我们在Golang网络编程中,经常要遇到设置超时的需求,本文就来给大家详细介绍了Go语言利用time.After实现超时控制的相关内容,下面话不多说了,来一起看看详细的介绍吧。 场景: 假设业务中需调用服务接口A,要求超时时间为5秒,那么如何优雅、简洁的实现呢? 我们可以采用select+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
}
超时控制的代码实现:
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,当先接收到 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对自学php网的支持。 |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com