Goはtimeを採用する.Afterによるタイムアウト制御

1217 ワード

シーン:
ビジネスでサービスインタフェースAを呼び出し、タイムアウト時間を5秒とするとしたら、どのように優雅で簡潔に実現するのでしょうか.select+time.Afterの方式を採用することができ、非常に簡単で適用可能な実現である.
まず、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) 
time.After()は、time.Durationが長いときにtime.Timeのタイプのチャネルメッセージを返すことを示す.では,この関数に基づいて,タイマを実現し,ブロックがないことに相当する.
タイムアウト制御のコード実装:
package main

import (
    "time"
    "fmt"
)

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

    go func() {
        time.Sleep(time.Second * 2)

        ch 
channelを使用して、コヒーレント内のトラフィック戻り値を受信します.select文は、最初に返されるデータを待つchannelをブロックし、time.Afterのチャネルデータを先に受信すると、selectはブロックを停止し、caseのコードを実行する.このとき,ビジネスコードのタイムアウト処理が実現された.
原文住所:https://shockerli.net/post/go...