本文作者:anker
前言
context.Context 非常重要肖爵!
context.Context 非常重要!
context.Context 非常重要臀脏!
源碼
go1.17.6的 context.Context 源碼劝堪,建議所有 golang developer 都讀一讀,在舊版本沒有那么多解釋文字揉稚,在最新的版本補充了很詳細的說明秒啦,甚至樣例,足以說明 context.Context 在 golang 中的重要性搀玖。
這里大概講解一下提供的方法及其作用余境,后面會詳細舉例
method | 作用 |
---|---|
Deadline() (deadline time.Time, ok bool) | 返回 Context 所控制的 deadline,ok表示是否有設置 deadline灌诅;一般用于 goroutine 控制超時時間 |
Done() <-chan struct{} | 返回一個 chan芳来,當 Context 被 cancel 或者達到 dealine的時候,此 chan 會被 close |
Err() error | Done 方法返回的 chan 被 close 以后有用猜拾,返回是什么原因被 close |
Value(key interface{}) interface{} | 通過傳入 key 獲取 value即舌,用于 Context 鏈式傳遞值 |
如果暫時不想閱讀源碼,可以先跳過這小節(jié)挎袜,后面都會講到顽聂。當然自行看看會更加清晰肥惭!
Context 存在的意義?
先給一個定論:Context 用于協(xié)程生命周期的管理芜飘,包括值傳遞
务豺,控制傳遞
。
首先我們先來看看 context 包的常用方法
- func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
- func WithValue(parent Context, key, val interface{}) Context
- func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
- func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
不難看出嗦明,上面幾個方法,通過父 Context 和一些參數(shù)派生出新的 Context 和 CancelFunc(非必須)蚪燕。這里 CancelFunc 的作用是通知新的 Context 以及往后通過他派生出來的 Context 進行結(jié)束娶牌。
那么通過派生行為,可以把 Context 管理的值
和控制行為
傳遞下去馆纳。
那么 Context 的作用诗良,其實也很明顯了:
作用 | 樣例 |
---|---|
管理生命周期參數(shù) | 通過 Context 傳遞 RequestId 打日志從 Context 讀取,把一個請求內(nèi)的日志串起來 |
管理控制行為 | 監(jiān)聽進程關(guān)閉信號量鲁驶,通過 Context 通知協(xié)程盡快結(jié)束 |
舉例
參數(shù)傳遞
這里以 http 請求通過 Context 傳遞 requestId 到日志組件作為例子鉴裹,下面是樣例代碼。
樣例代碼
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"sync/atomic"
)
const requestIdCtxKey = "requestIdCtxKey"
func main() {
counter := uint64(0)
r := gin.Default()
r.Use(func(c *gin.Context) {
// gin.Context 也實現(xiàn)了 context.Context interface
requestId := atomic.AddUint64(&counter, 1)
// 給每個請求設置 requestId
c.Set(requestIdCtxKey, requestId)
})
r.GET("/", func(c *gin.Context) {
// 讀取相應內(nèi)容钥弯,以 ctx.Context 讀取
getResponseMessage := func(ctx context.Context, username string) (message string) {
message = fmt.Sprintf("hello %s!", username)
logFunc(ctx, "response:"+message)
return
}
// 直接把 gin.Context 傳入
message := getResponseMessage(c, c.DefaultQuery("user", "guest"))
logFunc(c, "url:"+c.Request.URL.RequestURI())
c.String(http.StatusOK, message)
})
r.Run(":12222")
}
func logFunc(ctx context.Context, message string) {
requestId := ctx.Value(requestIdCtxKey)
id := requestId.(uint64)
log.Printf("requestId:%d message:%s\n", id, message)
}
執(zhí)行命令:
curl http://127.0.0.1:12222/?user=anker
http輸出:
hello anker!
標準輸出:
2022/04/03 21:18:43 requestId:1 message:response:hello anker!
2022/04/03 21:18:43 requestId:1 message:url:/?user=anker
控制傳遞
這里以控制協(xié)程結(jié)束為例径荔,下面是樣例代碼
package main
import (
"context"
"log"
"sync"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
// 五秒后通知 ctx 結(jié)束
time.AfterFunc(5*time.Second, func() {
cancel()
})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for ok := true; ok; {
select {
case <-ctx.Done():
// 監(jiān)聽到結(jié)束,設置循環(huán)結(jié)束條件
ok = false
if ctx.Err() != nil {
// 輸出退出原因
log.Println("context done,error:", ctx.Err().Error())
}
case <-ticker.C:
}
if !ok {
continue
}
// 每1秒輸出一次
log.Println("goroutine 1 ticker:", time.Now().Unix())
}
}()
wg.Add(1)
go func() {
defer wg.Done()
// 監(jiān)聽ctx結(jié)束
<-ctx.Done()
log.Println("goroutine 2 end")
}()
wg.Wait()
log.Println("exit ok")
}
標準輸出:
2022/04/03 21:32:50 goroutine 1 ticker: 1648992770
2022/04/03 21:32:51 goroutine 1 ticker: 1648992771
2022/04/03 21:32:52 goroutine 1 ticker: 1648992772
2022/04/03 21:32:53 goroutine 1 ticker: 1648992773
2022/04/03 21:32:54 goroutine 2 end
2022/04/03 21:32:54 goroutine 1 ticker: 1648992774
2022/04/03 21:32:54 context done,error: context canceled
2022/04/03 21:32:54 exit ok
延伸開來脆霎,可以通過在函數(shù)調(diào)用鏈中傳遞 Context 总处,實現(xiàn)在上層函數(shù)一些機制(超時、可用性檢測)通知下層方法盡快結(jié)束睛蛛。
例如 Mysql 查詢鹦马,Redis 操作,調(diào)用這些組件的庫一般都會提供 Context 作為函數(shù)第一個值忆肾,其實就是用作控制行為傳遞荸频。
而且強烈建議 Context 作為函數(shù)的參數(shù)時,放第一個參數(shù)位置客冈。
最后
通過一些樣例旭从,現(xiàn)在應該對 Context 有更深的了解了。不妨再滑動上去看看源碼中關(guān)于 Context 的注釋郊酒,會有更深刻的認識遇绞。