假設(shè)有一個(gè)耗時(shí)業(yè)務(wù)如下,將其改造成超時(shí)關(guān)閉
// demo 假設(shè)耗時(shí)業(yè)務(wù)
func demo() string {
time.Sleep(time.Second * 3)
return "success"
}
改造方法如下
// demo
// 將結(jié)果改由channel刻蟹,并且立刻返回
// 真正的業(yè)務(wù)處理放到協(xié)程里
func demo() chan string {
result := make(chan string)
// 處理原有邏輯,避免阻塞
go func() {
time.Sleep(time.Second * 3)
result <- "success"
}()
return result
}
func run() (interface{}, error) {
c := demo()
select {
case res := <-c:
return res, nil
case <-time.After(time.Second * 2): // 超時(shí)處理
return nil, fmt.Errorf("timeout")
}
}
func main() {
fmt.Println(run())
}