Go Context庫 使用基本示例
為什么需要Context
在 Go http包的Server中,每一個請求在都有一個對應(yīng)的 goroutine 去處理。請求處理函數(shù)通常會啟動額外的 goroutine 用來訪問后端服務(wù),比如數(shù)據(jù)庫和RPC服務(wù)。
用來處理一個請求的 goroutine 通常需要訪問一些與請求特定的數(shù)據(jù),比如終端用戶的身份認(rèn)證信息、驗證相關(guān)的token、請求的截止時間。
當(dāng)一個請求被取消或超時時,所有用來處理該請求的 goroutine 都應(yīng)該迅速退出,然后系統(tǒng)才能釋放這些 goroutine 占用的資源。
基本示例
在 Go 語言中,sync.WaitGroup
是一個用于控制多個協(xié)程(goroutine)的同步工具,它允許主協(xié)程等待多個并發(fā)協(xié)程完成工作。WaitGroup
通過計數(shù)器來跟蹤多個協(xié)程的完成狀態(tài),每個協(xié)程在開始執(zhí)行前調(diào)用 WaitGroup
的 Add
方法增加計數(shù),執(zhí)行完成后調(diào)用 Done
方法減少計數(shù)。當(dāng)計數(shù)器歸零時,表示所有協(xié)程都已完成,主協(xié)程可以繼續(xù)執(zhí)行。
主要方法
Add(delta int)
:增加WaitGroup
的計數(shù)器,通常在啟動協(xié)程之前調(diào)用。delta
可以是任何整數(shù),通常用于跟蹤需要等待的協(xié)程數(shù)量。Done()
:減少WaitGroup
的計數(shù)器,通常在協(xié)程完成工作后調(diào)用。Wait()
:阻塞調(diào)用Wait
的協(xié)程,直到WaitGroup
的計數(shù)器歸零。
package main import ( "fmt" "sync" "time" ) var wg sync.WaitGroup // 初始的例子 func worker() { for { fmt.Println("worker") time.Sleep(time.Second) } // 如何接收外部命令實現(xiàn)退出 wg.Done() } func main() { wg.Add(1) go worker() // 如何優(yōu)雅的實現(xiàn)結(jié)束子goroutine wg.Wait() fmt.Println("over") }
全局變量方式
全局變量方式存在的問題:
1. 使用全局變量在跨包調(diào)用時不容易統(tǒng)一
2. 如果worker中再啟動goroutine,就不太好控制了。
package main import ( "fmt" "sync" "time" ) var wg sync.WaitGroup var exit bool func worker() { for { fmt.Println("worker") time.Sleep(time.Second) if exit { break } } wg.Done() } func main() { wg.Add(1) go worker() time.Sleep(time.Second * 3) // sleep3秒以免程序過快退出 exit = true // 修改全局變量實現(xiàn)子goroutine的退出 wg.Wait() fmt.Println("over") }
通道方式
管道方式存在的問題:
1. 使用全局變量在跨包調(diào)用時不容易實現(xiàn)規(guī)范和統(tǒng)一,需要維護一個共用的channel
package main import ( "fmt" "sync" "time" ) var wg sync.WaitGroup func worker(exitChan chan struct{}) { LOOP: for { fmt.Println("worker") time.Sleep(time.Second) select { case <-exitChan: // 等待接收上級通知 break LOOP default: } } wg.Done() } func main() { var exitChan = make(chan struct{}) wg.Add(1) go worker(exitChan) time.Sleep(time.Second * 3) // sleep3秒以免程序過快退出 exitChan <- struct{}{} // 給子goroutine發(fā)送退出信號 close(exitChan) wg.Wait() fmt.Println("over") }
官方版的方案
package main import ( "context" "fmt" "sync" "time" ) var wg sync.WaitGroup func worker(ctx context.Context) { LOOP: for { fmt.Println("worker") time.Sleep(time.Second) select { case <-ctx.Done(): // 等待上級通知 break LOOP default: } } wg.Done() } func main() { ctx, cancel := context.WithCancel(context.Background()) wg.Add(1) go worker(ctx) time.Sleep(time.Second * 3) cancel() // 通知子goroutine結(jié)束 wg.Wait() fmt.Println("over") }
當(dāng)子goroutine又開啟另外一個goroutine時,只需要將ctx傳入即可:
package main import ( "context" "fmt" "sync" "time" ) var wg sync.WaitGroup func worker(ctx context.Context) { go worker2(ctx) LOOP: for { fmt.Println("worker") time.Sleep(time.Second) select { case <-ctx.Done(): // 等待上級通知 break LOOP default: } } wg.Done() } func worker2(ctx context.Context) { LOOP: for { fmt.Println("worker2") time.Sleep(time.Second) select { case <-ctx.Done(): // 等待上級通知 break LOOP default: } } } func main() { ctx, cancel := context.WithCancel(context.Background()) wg.Add(1) go worker(ctx) time.Sleep(time.Second * 3) cancel() // 通知子goroutine結(jié)束 wg.Wait() fmt.Println("over") }
Context初識
Go1.7加入了一個新的標(biāo)準(zhǔn)庫context
,它定義了Context
類型,專門用來簡化對于處理單個請求的多個 goroutine 之間與請求域的數(shù)據(jù)、取消信號、截止時間等相關(guān)操作,這些操作可能涉及多個 API 調(diào)用。
對服務(wù)器傳入的請求應(yīng)該創(chuàng)建上下文,而對服務(wù)器的傳出調(diào)用應(yīng)該接受上下文。它們之間的函數(shù)調(diào)用鏈必須傳遞上下文,或者可以使用WithCancel
、WithDeadline
、WithTimeout
或WithValue
創(chuàng)建的派生上下文。當(dāng)一個上下文被取消時,它派生的所有上下文也被取消。
Context接口
context.Context
是一個接口,該接口定義了四個需要實現(xiàn)的方法。具體簽名如下:
type Context interface { Deadline() (deadline time.Time, ok bool) Done() <-chan struct{} Err() error Value(key interface{}) interface{} }
其中:
Deadline
方法需要返回當(dāng)前Context
被取消的時間,也就是完成工作的截止時間(deadline);Done
方法需要返回一個Channel
,這個Channel會在當(dāng)前工作完成或者上下文被取消之后關(guān)閉,多次調(diào)用Done
方法會返回同一個Channel;Err
方法會返回當(dāng)前Context
結(jié)束的原因,它只會在Done
返回的Channel被關(guān)閉時才會返回非空的值;- 如果當(dāng)前
Context
被取消就會返回Canceled
錯誤; - 如果當(dāng)前
Context
超時就會返回DeadlineExceeded
錯誤;
- 如果當(dāng)前
Value
方法會從Context
中返回鍵對應(yīng)的值,對于同一個上下文來說,多次調(diào)用Value
并傳入相同的Key
會返回相同的結(jié)果,該方法僅用于傳遞跨API和進(jìn)程間跟請求域的數(shù)據(jù);
Background()和TODO()
Go內(nèi)置兩個函數(shù):Background()
和TODO()
,這兩個函數(shù)分別返回一個實現(xiàn)了Context
接口的background
和todo
。我們代碼中最開始都是以這兩個內(nèi)置的上下文對象作為最頂層的partent context
,衍生出更多的子上下文對象。
Background()
主要用于main函數(shù)、初始化以及測試代碼中,作為Context這個樹結(jié)構(gòu)的最頂層的Context,也就是根Context。
TODO()
,它目前還不知道具體的使用場景,如果我們不知道該使用什么Context的時候,可以使用這個。
background
和todo
本質(zhì)上都是emptyCtx
結(jié)構(gòu)體類型,是一個不可取消,沒有設(shè)置截止時間,沒有攜帶任何值的Context。
With系列函數(shù)
此外,context
包中還定義了四個With系列函數(shù)。
WithCancel
WithCancel
的函數(shù)簽名如下:
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
WithCancel
返回帶有新Done通道的父節(jié)點的副本。當(dāng)調(diào)用返回的cancel函數(shù)或當(dāng)關(guān)閉父上下文的Done通道時,將關(guān)閉副本上下文的Done通道,無論先發(fā)生什么情況。
取消此上下文將釋放與其關(guān)聯(lián)的資源,因此代碼應(yīng)該在此上下文中運行的操作完成后立即調(diào)用cancel。
func gen(ctx context.Context) <-chan int { dst := make(chan int) n := 1 go func() { for { select { case <-ctx.Done(): return // return結(jié)束該goroutine,防止泄露 case dst <- n: n++ } } }() return dst } func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() // 當(dāng)我們?nèi)⊥晷枰恼麛?shù)后調(diào)用cancel for n := range gen(ctx) { fmt.Println(n) if n == 5 { break } } }
上面的示例代碼中,gen
函數(shù)在單獨的goroutine中生成整數(shù)并將它們發(fā)送到返回的通道。 gen的調(diào)用者在使用生成的整數(shù)之后需要取消上下文,以免gen
啟動的內(nèi)部goroutine發(fā)生泄漏。
WithDeadline
WithDeadline
的函數(shù)簽名如下:
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
返回父上下文的副本,并將deadline調(diào)整為不遲于d。如果父上下文的deadline已經(jīng)早于d,則WithDeadline(parent, d)在語義上等同于父上下文。當(dāng)截止日過期時,當(dāng)調(diào)用返回的cancel函數(shù)時,或者當(dāng)父上下文的Done通道關(guān)閉時,返回上下文的Done通道將被關(guān)閉,以最先發(fā)生的情況為準(zhǔn)。
取消此上下文將釋放與其關(guān)聯(lián)的資源,因此代碼應(yīng)該在此上下文中運行的操作完成后立即調(diào)用cancel。
func main() { d := time.Now().Add(50 * time.Millisecond) ctx, cancel := context.WithDeadline(context.Background(), d) // 盡管ctx會過期,但在任何情況下調(diào)用它的cancel函數(shù)都是很好的實踐。 // 如果不這樣做,可能會使上下文及其父類存活的時間超過必要的時間。 defer cancel() select { case <-time.After(1 * time.Second): fmt.Println("overslept") case <-ctx.Done(): fmt.Println(ctx.Err()) } }
上面的代碼中,定義了一個50毫秒之后過期的deadline,然后我們調(diào)用context.WithDeadline(context.Background(), d)
得到一個上下文(ctx)和一個取消函數(shù)(cancel),然后使用一個select讓主程序陷入等待:等待1秒后打印overslept
退出或者等待ctx過期后退出。
在上面的示例代碼中,因為ctx 50毫秒后就會過期,所以ctx.Done()
會先接收到context到期通知,并且會打印ctx.Err()的內(nèi)容。
WithTimeout
WithTimeout
的函數(shù)簽名如下:
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithTimeout
返回WithDeadline(parent, time.Now().Add(timeout))
。
取消此上下文將釋放與其相關(guān)的資源,因此代碼應(yīng)該在此上下文中運行的操作完成后立即調(diào)用cancel,通常用于數(shù)據(jù)庫或者網(wǎng)絡(luò)連接的超時控制。具體示例如下:
package main import ( "context" "fmt" "sync" "time" ) // context.WithTimeout var wg sync.WaitGroup func worker(ctx context.Context) { LOOP: for { fmt.Println("db connecting ...") time.Sleep(time.Millisecond * 10) // 假設(shè)正常連接數(shù)據(jù)庫耗時10毫秒 select { case <-ctx.Done(): // 50毫秒后自動調(diào)用 break LOOP default: } } fmt.Println("worker done!") wg.Done() } func main() { // 設(shè)置一個50毫秒的超時 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50) wg.Add(1) go worker(ctx) time.Sleep(time.Second * 5) cancel() // 通知子goroutine結(jié)束 wg.Wait() fmt.Println("over") }
WithValue
WithValue
函數(shù)能夠?qū)⒄埱笞饔糜虻臄?shù)據(jù)與 Context 對象建立關(guān)系。聲明如下:
func WithValue(parent Context, key, val interface{}) Context
WithValue
返回父節(jié)點的副本,其中與key關(guān)聯(lián)的值為val。
僅對API和進(jìn)程間傳遞請求域的數(shù)據(jù)使用上下文值,而不是使用它來傳遞可選參數(shù)給函數(shù)。
所提供的鍵必須是可比較的,并且不應(yīng)該是string
類型或任何其他內(nèi)置類型,以避免使用上下文在包之間發(fā)生沖突。WithValue
的用戶應(yīng)該為鍵定義自己的類型。為了避免在分配給interface{}時進(jìn)行分配,上下文鍵通常具有具體類型struct{}
?;蛘撸瑢?dǎo)出的上下文關(guān)鍵變量的靜態(tài)類型應(yīng)該是指針或接口。
package main import ( "context" "fmt" "sync" "time" ) // context.WithValue type TraceCode string var wg sync.WaitGroup func worker(ctx context.Context) { key := TraceCode("TRACE_CODE") traceCode, ok := ctx.Value(key).(string) // 在子goroutine中獲取trace code if !ok { fmt.Println("invalid trace code") } LOOP: for { fmt.Printf("worker, trace code:%s\n", traceCode) time.Sleep(time.Millisecond * 10) // 假設(shè)正常連接數(shù)據(jù)庫耗時10毫秒 select { case <-ctx.Done(): // 50毫秒后自動調(diào)用 break LOOP default: } } fmt.Println("worker done!") wg.Done() } func main() { // 設(shè)置一個50毫秒的超時 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50) // 在系統(tǒng)的入口中設(shè)置trace code傳遞給后續(xù)啟動的goroutine實現(xiàn)日志數(shù)據(jù)聚合 ctx = context.WithValue(ctx, TraceCode("TRACE_CODE"), "12512312234") wg.Add(1) go worker(ctx) time.Sleep(time.Second * 5) cancel() // 通知子goroutine結(jié)束 wg.Wait() fmt.Println("over") }
使用Context的注意事項
- 推薦以參數(shù)的方式顯示傳遞Context
- 以Context作為參數(shù)的函數(shù)方法,應(yīng)該把Context作為第一個參數(shù)。
- 給一個函數(shù)方法傳遞Context的時候,不要傳遞nil,如果不知道傳遞什么,就使用
- context.TODO()Context的Value相關(guān)方法應(yīng)該傳遞請求域的必要數(shù)據(jù),不應(yīng)該用于傳遞可選參數(shù)
- Context是線程安全的,可以放心的在多個goroutine中傳遞
客戶端超時取消示例
調(diào)用服務(wù)端API時如何在客戶端實現(xiàn)超時控制?
server端
// context_timeout/server/main.go package main import ( "fmt" "math/rand" "net/http" "time" ) // server端,隨機出現(xiàn)慢響應(yīng) func indexHandler(w http.ResponseWriter, r *http.Request) { number := rand.Intn(2) if number == 0 { time.Sleep(time.Second * 10) // 耗時10秒的慢響應(yīng) fmt.Fprintf(w, "slow response") return } fmt.Fprint(w, "quick response") } func main() { http.HandleFunc("/", indexHandler) err := http.ListenAndServe(":8000", nil) if err != nil { panic(err) } }
client端
// context_timeout/client/main.go package main import ( "context" "fmt" "io/ioutil" "net/http" "sync" "time" ) // 客戶端 type respData struct { resp *http.Response err error } func doCall(ctx context.Context) { transport := http.Transport{ // 請求頻繁可定義全局的client對象并啟用長鏈接 // 請求不頻繁使用短鏈接 DisableKeepAlives: true, } client := http.Client{ Transport: &transport, } respChan := make(chan *respData, 1) req, err := http.NewRequest("GET", "http://127.0.0.1:8000/", nil) if err != nil { fmt.Printf("new requestg failed, err:%v\n", err) return } req = req.WithContext(ctx) // 使用帶超時的ctx創(chuàng)建一個新的client request var wg sync.WaitGroup wg.Add(1) defer wg.Wait() go func() { resp, err := client.Do(req) fmt.Printf("client.do resp:%v, err:%v\n", resp, err) rd := &respData{ resp: resp, err: err, } respChan <- rd wg.Done() }() select { case <-ctx.Done(): //transport.CancelRequest(req) fmt.Println("call api timeout") case result := <-respChan: fmt.Println("call server api success") if result.err != nil { fmt.Printf("call server api failed, err:%v\n", result.err) return } defer result.resp.Body.Close() data, _ := ioutil.ReadAll(result.resp.Body) fmt.Printf("resp:%v\n", string(data)) } } func main() { // 定義一個100毫秒的超時 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*100) defer cancel() // 調(diào)用cancel釋放子goroutine資源 doCall(ctx) }
到此這篇關(guān)于 Go Context庫 使用的文章就介紹到這了,更多相關(guān) Go Context庫 使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語言如何高效的進(jìn)行字符串拼接(6種方式對比分析)
本文主要介紹了Go語言如何高效的進(jìn)行字符串拼接(6種方式對比分析),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08Golang空結(jié)構(gòu)體struct{}用途,你知道嗎
這篇文章主要介紹了Golang空結(jié)構(gòu)體struct{}用途,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01Go語言編程學(xué)習(xí)golang配置golint
這篇文章主要為大家介紹了Go語言編程學(xué)習(xí)golang配置golint的過程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-11-11golang包循環(huán)引用的幾種解決方案總結(jié)
golang有包循環(huán)引用問題,用過的應(yīng)該都知道,下面這篇文章主要給大家介紹了關(guān)于golang包循環(huán)引用的幾種解決方案,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09