Context
Go 語言中提供了 context 包,通過顯示傳遞 context, 實現請求級別的元數據、取消信號、終止信號的傳遞。context 包提供了從現有的上下文值(curContext)派生新的上下文值(newContext)的函數。 這些值會形成一個樹。 當一個 context 被取消或者超時時,從它派生的所有 context 也都被取消。利用這個特性可以實現服務請求調用的超時控制。當一個請求被取消或超時時,處理該請求的所有 goroutine 都可以快速退出(fail fast),這樣系統就可以回收它們正在使用的資源。
從 Go 項目的編程風格看,一種常見的作法是將 context 作爲函數的第一個參數,通過顯示傳遞的方式,貫穿請求的全流程。這樣做的代價是所有的函數入參都將帶上 context 信息 (trade-off)。
需要注意的是,context 通常是面向請求的,所以在使用 context 傳遞的數據一般是指請求的上下文信息,比如ip、traceId、用戶信息等。
Context 接口約定了5個方法
// A Context carries a deadline, cancellation signal, and request-scoped values
// across API boundaries. Its methods are safe for simultaneous use by multiple
// goroutines.
type Context interface {
// Done returns a channel that is closed when this Context is canceled
// or times out.
Done() <-chan struct{}
// Err indicates why this context was canceled, after the Done channel
// is closed.
Err() error
// Deadline returns the time when this Context will be canceled, if any.
Deadline() (deadline time.Time, ok bool)
// Value returns the value associated with key or nil if none.
Value(key interface{}) interface{}
}
- Deadline 方法返回當前 context 被取消的時間
- Done 方法返回一個 channel,這個 channel 會在當前工作完成或者上下文被取消之後關閉,多次調用Done方法會返回同一個channel
- Err方法會返回當前 context 結束的原因,它只會在Done返回的 context 被關閉時纔會返回非空的值,如果當前Context被取消就會返回 canceled 錯誤,如果當前 context 超時就會返回 DeadlineExceeded 錯誤
- Value方法會從 context 中返回鍵對應的值,對於同一個上下文來說,多次調用 Value 並傳入相同的 key會返回相同的結果
Derived contexts
context 包提供了很多派生方法的實現。譬如 WithCancel、WithTimeout 等。以下是 context 包的函數定義。
// Background returns an empty Context. It is never canceled, has no deadline,
// and has no values. Background is typically used in main, init, and tests,
// and as the top-level Context for incoming requests.
func Background() Context
// WithCancel returns a copy of parent with a new Done channel. The returned
// context's Done channel is closed when the returned cancel function is called
// or when the parent context's Done channel is closed, whichever happens first.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {}
// A CancelFunc cancels a Context.
type CancelFunc func()
// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete:
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {}
// WithValue returns a copy of parent in which the value associated with key is
// val.
//
// Use context Values only for request-scoped data that transits processes and
// APIs, not for passing optional parameters to functions.
func WithValue(parent Context, key, val interface{}) Context {}
// A valueCtx carries a key-value pair. It implements Value for that key and
// delegates all other calls to the embedded Context.
type valueCtx struct {
Context
key, val interface{}
}
// WithDeadline returns a copy of the parent context with the deadline adjusted
// to be no later than d. If the parent's deadline is already earlier than d,
// WithDeadline(parent, d) is semantically equivalent to parent. The returned
// context's Done channel is closed when the deadline expires, when the returned
// cancel function is called, or when the parent context's Done channel is
// closed, whichever happens first.
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {}
值得注意的時,WithValue 一對 key/value 時,它將父節點的 context 嵌入到子 context, 並在節點中保存 key/value 數據。Value() 查詢 key 對應的數據時,會先從當前 context 查詢,如果查詢不到,會遞歸查詢父 context 中的數據。所以 WithValue 實際上類似一個鏈表,不適合大量使用。
Context 使用示例
WithCancel
func get(ctx context.Context) <-chan int {
num := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
fmt.Println(ctx.Err().Error()) //context canceled
close(num) //需要關閉 channel 否則如果還有消費者消費會死鎖
return // return結束該goroutine,防止泄露
case num <- n:
n++
}
}
}()
return num
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
number := get(ctx)
fmt.Println(<-number)
fmt.Println(<-number)
fmt.Println(<-number)
cancel()
fmt.Println(<-number)
}
WithTimeout
var wg sync.WaitGroup
func worker(ctx context.Context) {
i := 1
Loop:
for i < 1000 {
i++
fmt.Println("i=", i)
time.Sleep(time.Millisecond * 20)
select {
case <-ctx.Done():
fmt.Println(ctx.Err().Error())//context deadline exceeded
break Loop
default:
}
}
wg.Done()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
wg.Add(1)
go worker(ctx)
time.Sleep(time.Second * 1)
cancel()
wg.Wait()
fmt.Println("over")
}
WithDeadline
func main() {
d := time.Now().Add(50 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), d)
defer cancel()
for {
select {
case <-time.After(10 * time.Millisecond):
fmt.Println("next")
case <-ctx.Done():
fmt.Println(ctx.Err().Error()) //context deadline exceeded
return
}
}
}
WithValue
const (
KEY_CODE = "demo"
)
var w sync.WaitGroup
func worker1(ctx context.Context) {
key := KEY_CODE
traceCode, ok := ctx.Value(key).(string)
if !ok {
fmt.Println("invalid")
}
for {
fmt.Printf("worker1, trace code:%s\n", traceCode)
time.Sleep(time.Millisecond * 10)
select {
case <-ctx.Done():
fmt.Println(ctx.Err().Error())
w.Done()
return
default:
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
ctx = context.WithValue(ctx, KEY_CODE, "123456")
w.Add(1)
go worker1(ctx)
// time.Sleep(time.Second * 1)
cancel()
w.Wait()
fmt.Println("over")
}