一文帶你深入理解Golang Context包
1. 基本原理
1.1 Context 包的介紹
在 Go 語言中,Context 包是用于傳遞請求范圍數(shù)據(jù)、取消信號和截止時間的機制。它通常被用來處理 goroutine 之間的通信和取消。Context 包是 Go 語言內置的,它可以很方便地使用,而不需要額外的依賴。
Context 包是一個輕量級的工具,它提供了一個標準的接口,用于在 goroutine 之間傳遞請求范圍的數(shù)據(jù)、取消信號和截止時間。Context 包實現(xiàn)了一種類似于樹狀結構的數(shù)據(jù)結構,其中每個節(jié)點都表示一個請求范圍。每個節(jié)點都有一個唯一的 key-value 對,其中 key 是一個 interface{} 類型的值,而 value 則是任何類型的值。Context 包還提供了一個可選的超時機制,用于在一定時間后自動取消請求。
Context 包的核心是一個 Context 接口,它定義了一些方法,用于獲取請求范圍數(shù)據(jù)、取消請求和處理超時。
?type Context interface { ? ? ?Deadline() (deadline time.Time, ok bool) ? ? ?Done() <-chan struct{} ? ? ?Err() error ? ? ?Value(key interface{}) interface{} ?}
- Deadline() 方法返回截止時間和一個布爾值,指示截止時間是否已經(jīng)設置。
- Done() 方法返回一個只讀的 channel,當請求被取消或超時時,該 channel 將被關閉。
- Err() 方法返回一個錯誤,指示為什么請求被取消。
- Value() 方法返回與給定key相關聯(lián)的值,如果沒有值,則返回 nil。
Context 包還提供了兩個用于創(chuàng)建 Context 的函數(shù):WithContext 和 Background。Background 函數(shù)返回一個空的 Context,而 WithContext 函數(shù)則根據(jù)給定的父 Context 創(chuàng)建一個新的 Context。
Context 包的基本原理是通過在 goroutine 之間傳遞 Context 來實現(xiàn)請求范圍數(shù)據(jù)、取消信號和截止時間的管理。當一個 goroutine 創(chuàng)建了一個新的 goroutine 時,它將 Context 作為參數(shù)傳遞給新的 goroutine。新的goroutine 可以使用這個 Context 來訪問請求范圍數(shù)據(jù)、接收取消信號和處理超時。
1.2 Context 的創(chuàng)建
在 Golang 中,Context 可以通過 WithCancel、WithDeadline、WithTimeout 和 WithValue 等函數(shù)來創(chuàng)建。下面分別介紹這些函數(shù)的用法和注意事項。
1.2.1 WithCancel
WithCancel 函數(shù)可以用于創(chuàng)建一個 Context 對象,并返回一個可取消的上下文和一個取消函數(shù)。當調用取消函數(shù)時,會通知所有的 Context 對象和其子 Context 對象,使它們都取消執(zhí)行。
?func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
下面是一個示例代碼:
?package main ?? ?import ( ? ? ?"context" ? ? ?"fmt" ? ? ?"time" ?) ?? ?func main() { ? ? ?parent := context.Background() ? ? ?ctx, cancel := context.WithCancel(parent) ? ? ?go func() { ? ? ? ? ?select { ? ? ? ? ?case <-ctx.Done(): ? ? ? ? ? ? ?fmt.Println(ctx.Err()) ? ? ? ? ? ? ?return ? ? ? ? ?case <-time.After(5 * time.Second): ? ? ? ? ? ? ?fmt.Println("work done") ? ? ? ? } ? ? }() ? ? ?time.Sleep(10 * time.Second) ? ? ?cancel() ? ? ?time.Sleep(1 * time.Second) ?}
在上面的代碼中,我們首先使用 context.Background() 函數(shù)創(chuàng)建一個根 Context 對象 parent,然后使用 WithCancel 函數(shù)創(chuàng)建一個子 Context 對象 ctx,并返回一個可取消的上下文和一個取消函數(shù) cancel。接下來,我們在一個 goroutine 中使用 select 語句監(jiān)聽 Context 對象的 Done 方法和 time.After 函數(shù)的返回值,如果 Done 方法返回一個非 nil 的 error,則說明 Context 已經(jīng)被取消,否則說明 time.After 函數(shù)已經(jīng)超時。在主函數(shù)中,我們調用 cancel 函數(shù)來通知 Context 對象和其子 Context 對象,使它們都取消執(zhí)行。最后,我們使用 time.Sleep 函數(shù)讓程序等待一段時間,以便觀察 Context 的執(zhí)行情況。
1.2.2 WithDeadline
WithDeadline 函數(shù)可以用于創(chuàng)建一個 Context 對象,并返回一個截止時間和一個取消函數(shù)。當超過截止時間時,會自動通知所有的 Context 對象和其子 Context 對象,使它們都取消執(zhí)行。
?func WithDeadline(parent Context, deadline time.Time) (ctx Context, cancel CancelFunc)
下面是一個示例代碼:
?package main ?? ?import ( ? ? ?"context" ? ? ?"fmt" ? ? ?"time" ?) ?? ?func main() { ? ? ?parent := context.Background() ? ? ?ctx, cancel := context.WithDeadline(parent, time.Now().Add(5*time.Second)) ? ? ?go func() { ? ? ? ? ?select { ? ? ? ? ?case <-ctx.Done(): ? ? ? ? ? ? ?fmt.Println(ctx.Err()) ? ? ? ? ? ? ?return ? ? ? ? ?case <-time.After(10 * time.Second): ? ? ? ? ? ? ?fmt.Println("work done") ? ? ? ? } ? ? }() ? ? ?time.Sleep(20 * time.Second) ? ? ?cancel() ? ? ?time.Sleep(1 * time.Second) ?}
在上面的代碼中,我們首先使用 context.Background() 函數(shù)創(chuàng)建一個根 Context 對象 parent,然后使用 WithDeadline 函數(shù)創(chuàng)建一個子 Context 對象 ctx,并返回一個截止時間和一個取消函數(shù) cancel。接下來,我們在一個 goroutine 中使用 select 語句監(jiān)聽 Context 對象的 Done 方法和 time.After 函數(shù)的返回值,如果 Done 方法返回一個非 nil 的 error,則說明 Context 已經(jīng)被取消,否則說明 time.After 函數(shù)已經(jīng)超時。在主函數(shù)中,我們調用 cancel 函數(shù)來通知 Context 對象和其子 Context 對象,使它們都取消執(zhí)行。最后,我們使用 time.Sleep 函數(shù)讓程序等待一段時間,以便觀察 Context 的執(zhí)行情況。
1.2.3 WithTimeout
WithTimeout 函數(shù)可以用于創(chuàng)建一個 Context 對象,并返回一個超時時間和一個取消函數(shù)。當超過超時時間時,會自動通知所有的 Context 對象和其子 Context 對象,使它們都取消執(zhí)行。
?func WithTimeout(parent Context, timeout time.Duration) (ctx Context, cancel CancelFunc)
下面是一個示例代碼:
?package main ?? ?import ( ? ? ?"context" ? ? ?"fmt" ? ? ?"time" ?) ?? ?func main() { ? ? ?parent := context.Background() ? ? ?ctx, cancel := context.WithTimeout(parent, 5*time.Second) ? ? ?go func() { ? ? ? ? ?select { ? ? ? ? ?case <-ctx.Done(): ? ? ? ? ? ? ?fmt.Println(ctx.Err()) ? ? ? ? ? ? ?return ? ? ? ? ?case <-time.After(10 * time.Second): ? ? ? ? ? ? ?fmt.Println("work done") ? ? ? ? } ? ? }() ? ? ?time.Sleep(20 * time.Second) ? ? ?cancel() ? ? ?time.Sleep(1 * time.Second) ?}
在上面的代碼中,我們首先使用 context.Background() 函數(shù)創(chuàng)建一個根 Context 對象 parent,然后使用 WithTimeout 函數(shù)創(chuàng)建一個子 Context 對象 ctx,并返回一個超時時間和一個取消函數(shù) cancel。接下來,我們在一個 goroutine 中使用 select 語句監(jiān)聽 Context 對象的 Done 方法和 time.After 函數(shù)的返回值,如果 Done 方法返回一個非 nil 的 error,則說明 Context 已經(jīng)被取消,否則說明 time.After 函數(shù)已經(jīng)超時。在主函數(shù)中,我們調用 cancel 函數(shù)來通知 Context 對象和其子 Context 對象,使它們都取消執(zhí)行。最后,我們使用 time.Sleep 函數(shù)讓程序等待一段時間,以便觀察 Context 的執(zhí)行情況。
1.2.4 WithValue
WithValue 函數(shù)可以用于創(chuàng)建一個 Context 對象,并返回一個包含指定值的 Context 對象。這個值可以是任意類型的數(shù)據(jù),可以是基本類型、結構體或者指針等。需要注意的是,這個值只在當前 Context 對象及其子 Context 對象中有效,對于其他 Context 對象來說是不可見的。
?func WithValue(parent Context, key interface{}, val interface{}) Context
下面是一個示例代碼:
?package main ?? ?import ( ? ? ?"context" ? ? ?"fmt" ?) ?? ?type userKey struct{} ?? ?func main() { ? ? ?parent := context.Background() ? ? ?ctx := context.WithValue(parent, userKey{}, "admin") ? ? ?go func() { ? ? ? ? ?if user, ok := ctx.Value(userKey{}).(string); ok { ? ? ? ? ? ? ?fmt.Printf("user is %s\n", user) ? ? ? ? } else { ? ? ? ? ? ? ?fmt.Println("user is not found") ? ? ? ? } ? ? }() ? ? ?select {} ?}
在上面的代碼中,我們首先使用 context.Background() 函數(shù)創(chuàng)建一個根 Context 對象 parent,然后使用 WithValue 函數(shù)創(chuàng)建一個子 Context 對象 ctx,并返回一個包含指定值的 Context 對象。接下來,我們在一個 goroutine 中使用 ctx.Value 函數(shù)獲取 Context 對象中的值,并判斷其類型是否為字符串類型。如果是,則輸出其值,否則輸出 “user is not found”。在主函數(shù)中,我們使用select語句使程序一直運行,以便觀察 Context 的執(zhí)行情況。
2. Context 的使用場景
2.1 并發(fā)控制
一個很典型的使用場景是,當我們需要同時啟動多個 goroutine 進行任務處理時,我們可以使用 Context 來控制這些 goroutine 的執(zhí)行。在每個 goroutine 中,我們都可以檢測 Context 對象是否被取消,如果是,則退出 goroutine 的執(zhí)行,否則繼續(xù)執(zhí)行。
下面是一個示例代碼:
?package main ?? ?import ( ? ? ?"context" ? ? ?"fmt" ? ? ?"sync" ?) ?? ?func worker(ctx context.Context, wg *sync.WaitGroup) { ? ? ?defer wg.Done() ? ? ?for { ? ? ? ? ?select { ? ? ? ? ?default: ? ? ? ? ? ? ?fmt.Println("work") ? ? ? ? ?case <-ctx.Done(): ? ? ? ? ? ? ?return ? ? ? ? } ? ? } ?} ?? ?func main() { ? ? ?parent := context.Background() ? ? ?ctx, cancel := context.WithCancel(parent) ? ? ?var wg sync.WaitGroup ? ? ?for i := 0; i < 3; i++ { ? ? ? ? ?wg.Add(1) ? ? ? ? ?go worker(ctx, &wg) ? ? } ? ? ?cancel() ? ? ?wg.Wait() ?}
在上面的代碼中,我們首先使用 context.Background() 函數(shù)創(chuàng)建一個根 Context 對象 parent,然后使用 WithCancel 函數(shù)創(chuàng)建一個子 Context 對象 ctx,并返回一個取消函數(shù) cancel。接下來,我們使用 sync.WaitGroup 來等待所有的 goroutine 執(zhí)行完成。在主函數(shù)中,我們啟動了三個 goroutine 來執(zhí)行任務,同時使用 cancel 函數(shù)來通知這些 goroutine 取消執(zhí)行。最后,我們使用Wait方法等待所有的 goroutine 執(zhí)行完成。
2.2 超時控制
另一個典型的使用場景是,當我們需要對一個操作設置一個超時時間時,我們可以使用 Context 來控制這個操作的執(zhí)行時間。在操作執(zhí)行超時時,我們可以通知 Context 對象和其子 Context 對象取消執(zhí)行。
下面是一個示例代碼:
?package main ?? ?import ( ? ? ?"context" ? ? ?"fmt" ? ? ?"time" ?) ?? ?func work(ctx context.Context) { ? ? ?for { ? ? ? ? ?select { ? ? ? ? ?default: ? ? ? ? ? ? ?fmt.Println("work") ? ? ? ? ?case <-ctx.Done(): ? ? ? ? ? ? ?fmt.Println("work done") ? ? ? ? ? ? ?return ? ? ? ? } ? ? } ?} ? ? ? ?func main() { ? ? ?parent := context.Background() ? ? ?ctx, cancel := context.WithTimeout(parent, time.Second*5) ? ? ?defer cancel() ? ? ?work(ctx) ?}
在上面的代碼中,我們首先使用 context.Background() 函數(shù)創(chuàng)建一個根 Context 對象 parent,然后使用 WithTimeout 函數(shù)創(chuàng)建一個子 Context 對象 ctx,并返回一個取消函數(shù) cancel。在 work 函數(shù)中,我們啟動一個無限循環(huán),不斷輸出 “work”。同時,我們使用 select 語句來等待 Context 對象被取消。在主函數(shù)中,我們使用 defer 語句調用 cancel 函數(shù),以確保 Context 對象被取消。由于我們在 WithTimeout 函數(shù)中設置了一個 5 秒的超時時間,因此當程序運行超過 5 秒時,work 函數(shù)就會停止執(zhí)行。
2.3 數(shù)據(jù)庫連接
在使用數(shù)據(jù)庫連接時,我們通常需要保證連接池中的連接數(shù)量不會超過一定的閾值。如果連接池中的連接數(shù)量超過了閾值,則需要等待連接釋放后再進行操作。在這種情況下,我們可以使用 Context 來控制連接的生命周期。
下面是一個示例代碼:
?package main ?? ?import ( ? ? ?"context" ? ? ?"database/sql" ? ? ?"fmt" ? ? ?"sync" ? ? ?"time" ?? ? ? ?_ "github.com/go-sql-driver/mysql" ?) ?? ?const maxConn = 5 ?? ?func main() { ? ? ?db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test") ? ? ?if err != nil { ? ? ? ? ?panic(err) ? ? } ? ? ?defer db.Close() ?? ? ? ?ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ? ? ?defer cancel() ?? ? ? ?connCh := make(chan *sql.Conn, maxConn) ? ? ?var wg sync.WaitGroup ? ? ?for i := 0; i < maxConn; i++ { ? ? ? ? ?wg.Add(1) ? ? ? ? ?go func() { ? ? ? ? ? ? ?defer wg.Done() ? ? ? ? ? ? ?for { ? ? ? ? ? ? ? ? ?select { ? ? ? ? ? ? ? ? ?case <-ctx.Done(): ? ? ? ? ? ? ? ? ? ? ?return ? ? ? ? ? ? ? ? ?default: ? ? ? ? ? ? ? ? ? ? ?if len(connCh) < maxConn { ? ? ? ? ? ? ? ? ? ? ? ? ?conn, err := db.Conn(ctx) ? ? ? ? ? ? ? ? ? ? ? ? ?if err != nil { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?fmt.Println(err) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?return ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? ? ? ?connCh <- conn ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? }() ? ? } ? ? ?wg.Wait() ?}
在上面的代碼中,我們首先使用 sql.Open 函數(shù)打開一個 MySQL 數(shù)據(jù)庫的連接,并返回一個 DB 對象 db。接下來,我們使用 WithTimeout 函數(shù)創(chuàng)建一個 Context 對象 ctx,并設置一個超時時間為 5 秒。同時,我們創(chuàng)建一個容量為 maxConn 的 channel 對象 connCh,用于存儲數(shù)據(jù)庫連接。在g oroutine 中,我們使用 select 語句等待 Context 對象被取消。在每次循環(huán)中,我們檢查連接池中連接的數(shù)量是否超過了閾值,如果沒有,則使用 db.Conn 函數(shù)從連接池中獲取一個新的連接,并將其存儲到 connCh 中。最后,我們使用 sync.WaitGroup 等待所有的 goroutine 執(zhí)行完成。
2.4 HTTP 請求
在使用 HTTP 請求時,我們通常需要設置一個超時時間,以確保請求能夠在規(guī)定的時間內得到響應。在這種情況下,我們可以使用 Context 來控制HTTP請求的執(zhí)行時間。
下面是一個示例代碼:
?package main ?? ?import ( ? ? ?"context" ? ? ?"fmt" ? ? ?"io/ioutil" ? ? ?"net/http" ? ? ?"time" ?) ?? ?func main() { ? ? ?client := http.DefaultClient ? ? ?ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ? ? ?defer cancel() ? ? ?req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.example.com", nil) ? ? ?if err != nil { ? ? ? ? ?fmt.Println(err) ? ? ? ? ?return ? ? } ?? ? ? ?resp, err := client.Do(req) ? ? ?if err != nil { ? ? ? ? ?fmt.Println(err) ? ? ? ? ?return ? ? } ? ? ?defer resp.Body.Close() ?? ? ? ?body, err := ioutil.ReadAll(resp.Body) ? ? ?if err != nil { ? ? ? ? ?fmt.Println(err) ? ? ? ? ?return ? ? } ?? ? ? ?fmt.Println(string(body)) ?}
在上面的代碼中,我們首先使用 http.DefaultClient 創(chuàng)建一個 HTTP 客戶端對象 client。接下來,我們使用 WithTimeout 函數(shù)創(chuàng)建一個 Context 對象 ctx,并設置一個超時時間為 5 秒。同時,我們使用 http.NewRequestWithContext 函數(shù)創(chuàng)建一個 HTTP 請求對象 req,并將 Context 對象 ctx 作為參數(shù)傳遞給該函數(shù)。在 Do 函數(shù)中,我們會自動將 Context 對象 ctx 傳遞給 HTTP 請求,并在超時時間到達后自動取消該請求。
2.5 gRPC 請求
在使用 gRPC 請求時,我們通常需要設置一個超時時間,以確保請求能夠在規(guī)定的時間內得到響應。在這種情況下,我們可以使用 Context 來控制 gRPC 請求的執(zhí)行時間。
下面是一個示例代碼:
?package main ?? ?import ( ? "context" ? "fmt" ? "log" ? "time" ?? ? pb "github.com/example/helloworld" ? "google.golang.org/grpc" ?) ?? ?const ( ? address ? ? = "localhost:50051" ? defaultName = "world" ?) ?? ?func main() { ? conn, err := grpc.Dial(address, grpc.WithInsecure()) ? if err != nil { ? log.Fatalf("did not connect: %v", err) ? } ? defer conn.Close() ?? ? c := pb.NewGreeterClient(conn) ?? ? ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ? defer cancel() ?? ? r, err := c.SayHello(ctx, &pb.HelloRequest{Name: defaultName}) ? if err != nil { ? log.Fatalf("could not greet: %v", err) ? } ? log.Printf("Greeting: %s", r.GetMessage()) ?}
在上面的代碼中,我們首先使用 grpc.Dial 函數(shù)創(chuàng)建一個 gRPC 客戶端連接對象 conn。接下來,我們使用 pb.NewGreeterClient 函數(shù)創(chuàng)建一個 GreeterClient 對象 c。然后,我們使用 WithTimeout 函數(shù)創(chuàng)建一個 Context 對象 ctx,并設置一個超時時間為 5 秒。最后,我們使用 GreeterClient 對象 c 的 SayHello 函數(shù)發(fā)送一個 gRPC 請求,并將 Context 對象 ctx 作為參數(shù)傳遞給該函數(shù)。在 SayHello 函數(shù)中,我們會自動將 Context 對象 ctx 傳遞給 gRPC 請求,并在超時時間到達后自動取消該請求。
3. 總結
通過本文的介紹,我們了解了 Golang 的 Context 包的基本原理、使用方法和示例代碼。Context 包是 Go 語言中實現(xiàn)并發(fā)控制和超時控制的重要工具之一,可以幫助我們更加靈活地控制程序的執(zhí)行。在實際應用中,我們可以使用 Context 包來實現(xiàn)一些復雜的功能,例如控制數(shù)據(jù)庫連接池、處理 HTTP 請求和 gRPC 請求等。通過學習和使用 Context 包,我們可以更好地實現(xiàn)并發(fā)控制和超時控制,提高程序的可靠性和穩(wěn)定性。
在使用 Context 包時,需要注意以下幾點:
- Context 對象是線程安全的,可以被多個 goroutine 同時訪問。
- 可以使用 WithCancel、WithDeadline 和 WithTimeout 函數(shù)來創(chuàng)建 Context 對象,并使用 context.Background 函數(shù)創(chuàng)建根 Context 對象。
- 在進行 goroutine 間的通信時,可以使用 Context 對象來傳遞消息和控制 goroutine 的執(zhí)行。
- 在使用第三方庫時,需要注意該庫是否支持 Context 功能,以便正確地使用 Context 包。
- 在使用 Context 包時,需要避免出現(xiàn) Context 濫用的情況,應該根據(jù)實際需要僅僅傳遞必要的 Context 對象,避免將 Context 對象傳遞到太多的函數(shù)中,導致程序難以維護和調試。
通過本文的介紹,相信你已經(jīng)對 Golang 的 Context 包有了更深入的了解和掌握。希望你可以在實際應用中靈活運用 Context 包,提高程序的效率和可靠性。
以上就是一文帶你深入理解Golang Context包的詳細內容,更多關于Golang Context包的資料請關注腳本之家其它相關文章!
相關文章
Go語言Http?Server框架實現(xiàn)一個簡單的httpServer
這篇文章主要為大家介紹了Go語言Http?Server框架實現(xiàn)一個簡單的httpServer抽象,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04