Goはtimeを採用する.Afterによるタイムアウト制御
シーン:
ビジネスでサービスインタフェースAを呼び出し、タイムアウト時間を5秒とするとしたら、どのように優雅で簡潔に実現するのでしょうか.
まず、
タイムアウト制御のコード実装:
原文住所:https://shockerli.net/post/go...
ビジネスでサービスインタフェース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...