Go 采用 time.After 实现超时控制

场景:
假设业务中需调用服务接口A,要求超时时间为5秒,那么如何优雅、简洁的实现呢?

我们可以采用select+time.After的方式,十分简单适用的实现。

time.After()表示time.Duration长的时候后返回一条time.Time类型的通道消息。那么,基于这个函数,就相当于实现了定时器,且是无阻塞的。

超时控制的代码实现:

package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan string)

	go func() {
		fmt.Println("go func start....")
		time.Sleep(time.Second * 2)

		ch <- "result"
	}()

	select {
	//第一个case里阻塞的时间只有比第二个case阻塞的时间长的时候, 才能执行第二个case
	case res := <-ch:
		fmt.Println(res)
	case <-time.After(time.Second * 1):
		fmt.Println("timeout")
	}
}


我们使用channel来接收协程里的业务返回值。
select语句阻塞等待最先返回数据的channel,当先接收到time.After的通道数据时,select则会停止阻塞并执行该case的代码。此时就已经实现了对业务代码的超时处理。

原文地址:https://www.cnblogs.com/nyist-xsk/p/11302743.html