[翻譯]GO并發(fā)模型三:基于Context編程

image.png

簡(jiǎn)書(shū)不維護(hù)了,歡迎關(guān)注我的知乎:波羅學(xué)的個(gè)人主頁(yè)

原文:Context-Based Programming in Go
作者:Gigi Sayfan

在GO中,我們需要有能力管理并發(fā)運(yùn)行中的goroutine,主要是指它的生命周期。那些失去控制的goroutine可能會(huì)進(jìn)入某個(gè)死循環(huán),從而導(dǎo)致其它等待中的goroutine死鎖或運(yùn)行太久。理想情況是,我們可以終止這些goroutine或使它們不不好的超時(shí)退出。

可以基于context編程。Go 1.7 引入了context包。它為我們提供了這些能力,同時(shí)我們也可以將某些變量與context關(guān)聯(lián)實(shí)現(xiàn)信息的跨界交流與傳遞。

在本教程中,你將會(huì)了解到context的輸入輸出以及何時(shí)和如何使用它,以避免濫用。

什么情況下使用

context是一種非常好的抽象。它讓你可以封裝一些與核心邏輯無(wú)關(guān)的信息,比如 請(qǐng)求ID、認(rèn)證Token和超時(shí)時(shí)間。這可以為我們帶來(lái)如下的一些好處:

  • 它有效地幫助我們把核心邏輯參數(shù)與運(yùn)行參數(shù)中分離開(kāi)來(lái)。
  • 它為我們制定了通用的操作規(guī)則和在邊界交流數(shù)據(jù)的方法。
  • 它為我們提供了一套標(biāo)準(zhǔn)的機(jī)制,在不修改函數(shù)簽名的情況下傳遞額外信息。

Context接口

如下是Context的所有接口信息:

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done <-chan struct{}
    Err() error
    Value(key interface{})  interface{}
}

下面介紹各個(gè)方法的作用。

Deadline()

當(dāng)執(zhí)行完成,context就應(yīng)被取消,此時(shí)Deadline()會(huì)返回相應(yīng)的時(shí)間。當(dāng)沒(méi)有設(shè)置最后期限,Deadline返回ok == false。多次調(diào)用Deadline返回結(jié)果相同。

Done()

Done()方法返回的是一個(gè)channel,它將在工作執(zhí)行完成即context應(yīng)該被取消的時(shí)候被關(guān)閉。連續(xù)調(diào)用Done()返回的結(jié)果相同。

  • context.WithCancel()返回cancel函數(shù),當(dāng)調(diào)用它時(shí),Done會(huì)被關(guān)閉;
  • context.WithDeadline()設(shè)置過(guò)期時(shí)間,當(dāng)過(guò)期后,Done會(huì)被關(guān)閉;
  • context.WithTimeout()設(shè)置超時(shí)時(shí)間,當(dāng)超時(shí)后,Done會(huì)被關(guān)閉;

可以在select語(yǔ)句中使用Done:

func Stream(ctx context.Context, out chan<- Value) error {
    for {
        v, err := DoSomething(ctx)
        if err != nil {
            return err
        }

        select {
        case <-ctx.Done():
            return ctx.Err()
        case out <- v:
        }
    }
}

可以讀下這篇文章Go并發(fā)模型:Pipeline和Cancellation,介紹很多關(guān)于如何使用Done取消context的例子。

Err()

只要Done是打開(kāi)狀態(tài),Err()返回nil。如果context被取消,它返回Canceled error。如果context到期或超時(shí),它返回DeadlineExceeded error。Done被關(guān)閉后,多次調(diào)用Err()返回結(jié)果相同。下面是一些定義:

// Canceled is the error returned by Context.Err when the context is canceled.
var Canceled = errors.New("context canceled")

// DeadlineExceeded is the error returned by Context.Err when the context's deadline passes.
var DeadlineExceeded error = deadlineExceededError{}

Value()

Value()通過(guò)key去調(diào)用與context關(guān)聯(lián)的value,如果context中與指定key對(duì)應(yīng)的值,返回nil。多次以相同key調(diào)用Value()返回結(jié)果相同。

Context中的Value僅僅用于在請(qǐng)求范圍內(nèi)不同程序和接口的數(shù)據(jù)轉(zhuǎn)化,不可用于其他的參數(shù)傳遞。

在Context,一個(gè)key代表一個(gè)具體的值。那些希望用Context存儲(chǔ)數(shù)據(jù)值的函數(shù)通常會(huì)在全局分配一個(gè)變量key,并用這個(gè)key作為參數(shù)調(diào)用context.WithValue和context.Value()。key支持任何類型。

Context的作用域

Contexts有作用范圍。你可以從已有的context作用域延伸出新的作用域。父級(jí)不能訪問(wèn)衍生的作用域的數(shù)據(jù),不過(guò)下級(jí)是可以訪問(wèn)父級(jí)作用域數(shù)據(jù)的。

Contexts是層級(jí)結(jié)構(gòu)。你可以通過(guò)context.Background()或context.TODO()創(chuàng)建contexts。無(wú)論何時(shí)你調(diào)用WithCancel、WithDeadline或WithTimeout,都會(huì)得到出新的context,同時(shí)會(huì)返回一個(gè)cancel函數(shù)。最重要的是當(dāng)父級(jí)的context被取消,所有的子級(jí)也將取消。

你應(yīng)該在main、init和tests中使用context.Background()。如果不知道該使用什么context,可以通過(guò)context.TODO()產(chǎn)生context。

注意,Background和TODO生成的context是不可取消的。

過(guò)期、超時(shí)和取消

如你所知,WithDeadline() 和 WithTimeout() 創(chuàng)建的contexts將會(huì)自動(dòng)取消,而WithCancel() 創(chuàng)建的context必須通過(guò)cancel()明確指定何時(shí)取消。其實(shí),它們都會(huì)返回一個(gè)cancel函數(shù),所以既沒(méi)有超時(shí)/過(guò)期,你依然可以通過(guò)cancel取消衍生的context。

讓我們看個(gè)例子。首先,contextDemo函數(shù)有兩個(gè)參數(shù),分別是name和context。它在一個(gè)無(wú)限循環(huán)中運(yùn)行,不停的在控制臺(tái)打印name和deadline(如果有的話)。然后sleep一秒。

package main

import (
    "fmt"
    "context"
    "time"
)

func contextDemo(name string, ctx context.Context) {
    for {
        if ok {
            fmt.Println(name, "will expire at:", deadline)
        } else {
            fmt.Println(name, "has no deadline")
        }
        time.Sleep(time.Second)
    }
}

主函數(shù)創(chuàng)建了三個(gè)contexts:

  • 三秒超時(shí)的timeoutContext;
  • 沒(méi)有過(guò)期時(shí)間的cancelContext;
  • 由cancelContext產(chǎn)生的從現(xiàn)在開(kāi)始4小時(shí)過(guò)期的deadlineContext;

然后,啟動(dòng)三個(gè)contextDemo的goroutine。它們并發(fā)執(zhí)行且每秒打印一次message。

主函數(shù)通過(guò)讀取timeoutContext的Done()來(lái)實(shí)現(xiàn)等待goroutine超時(shí)退出。一但三秒超時(shí),main函數(shù)就調(diào)用cancelFunc取消cancelContext中的goroutine,同時(shí)cancelContext衍生出來(lái)的4小時(shí)過(guò)期的deadlineContext的goroutine也將退出。

func main() {
    timeout := 3 * time.Second
    deadline := time.Now().Add(4 * time.Hour)
    timeOutContext, _ := context.WithTimeout(
        context.Background(), timeout)
    cancelContext, cancelFunc := context.withCancel(
        context.Background())
    deadlineContext, _ := context.WithDeadline(
        cancelContext, deadline)
        
    go contextDemo("[timeoutContext]", timeOutContext)
    go contextDemo("[cancelContext]", cancelContext)
    go contextDemo("[deadlineContext]", deadlineContext)
 
    // Wait for the timeout to expire
    <- timeOutContext.Done()
 
    // This will cancel the deadline context as well as its
    // child - the cancelContext
    fmt.Println("Cancelling the cancel context...")
    cancelFunc()
 
    <- cancelContext.Done()
    fmt.Println("The cancel context has been cancelled...")
 
    // Wait for both contexts to be cancelled
    <- deadlineContext.Done()
    fmt.Println("The deadline context has been cancelled...")       
}

下面是輸出結(jié)果:

[cancelContext] has no deadline
[deadlineContext] will expire at: 2017-07-29 09:06:02.34260363
[timeoutContext] will expire at: 2017-07-29 05:06:05.342603759
[cancelContext] has no deadline
[timeoutContext] will expire at: 2017-07-29 05:06:05.342603759
[deadlineContext] will expire at: 2017-07-29 09:06:02.34260363
[cancelContext] has no deadline
[timeoutContext] will expire at: 2017-07-29 05:06:05.342603759
[deadlineContext] will expire at: 2017-07-29 09:06:02.34260363
Cancelling the cancel context...
The cancel context has been cancelled...
The deadline context has been cancelled...

輸出結(jié)果不變。接下來(lái)是最佳實(shí)踐章節(jié),將介紹一些指導(dǎo)原則,以便于我們恰當(dāng)?shù)厥褂胏ontext數(shù)據(jù)傳遞。

最佳實(shí)踐

圍繞context數(shù)據(jù)傳遞的幾個(gè)最佳實(shí)踐:

  • 避免在context中傳遞函數(shù)參數(shù);
  • 在全局變量中為context中的數(shù)據(jù)分配一個(gè)對(duì)應(yīng)key;
  • 包中應(yīng)該為key定義一個(gè)不可導(dǎo)出的類型,以防止發(fā)生沖突;
  • 包中定義的key應(yīng)該為其在context存儲(chǔ)的數(shù)據(jù)提供類型安全訪問(wèn)方法;

HTTP請(qǐng)求的Context

context的常用場(chǎng)景之一就是在HTTP請(qǐng)求間傳遞信息。這些信息可能包含請(qǐng)求ID、認(rèn)證證書(shū)等。在GO1.7,標(biāo)準(zhǔn)庫(kù)net/http利用了context的優(yōu)勢(shì),并且已經(jīng)標(biāo)準(zhǔn)化,直接在request中加入了對(duì)context的支持。

func (r *Request) Context() context.Context
func (r *Request) WithContext(ctx context.Context) *Request

現(xiàn)在,我們可以使用一種標(biāo)準(zhǔn)方式把從headers中獲取到的requestId傳遞到最終的處理函數(shù)。WithRequestID() 處理函數(shù)從"X-Request-ID"頭部導(dǎo)出requestID并從正在使用的context中衍生出一個(gè)帶有requestID的context。然后把它傳遞給調(diào)用鏈的下一個(gè)處理函數(shù)。公共函數(shù)GetRequestID()為處理函數(shù)提供了訪問(wèn)RequestID的途徑,包括定義在其他包的處理函數(shù)。

const requestIDKey int = 0
 
func WithRequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(
        func(rw http.ResponseWriter, req *http.Request) {
            // Extract request ID from request header
            reqID := req.Header.Get("X-Request-ID")
            // Create new context from request context with 
            // the request ID
            ctx := context.WithValue(
                req.Context(), requestIDKey, reqID)
            // Create new request with the new context
            req = req.WithContext(ctx)
            // Let the next handler in the chain take over.
            next.ServeHTTP(rw, req)
        }
    )
}
 
func GetRequestID(ctx context.Context) string {
    ctx.Value(requestIDKey).(string)
}

func Handle(rw http.ResponseWriter, req *http.Request) {
    reqID := GetRequestID(req.Context())
    ...
}

func main() {
    handler := WithRequestID(http.HandlerFunc(Handle))
    http.ListenAndServe("/", handler)
}

總結(jié)

基于Context的編程為我們提供了一套標(biāo)準(zhǔn)和良好支持的方法,它解決了兩個(gè)常見(jiàn)的問(wèn)題:goroutine的生命周期管理和信息傳遞。

以最佳實(shí)踐為準(zhǔn),在合適的場(chǎng)景下使用contexts,你的編碼能力將會(huì)大幅提升。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容