伺服器開發利器golang context用法詳解

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

本文主要基於官方文檔Go Concurrency Patterns: Context以及視頻Advanced Go Concurrency Patterns的學習而得。

背景

在go伺服器中,對於每個請求的request都是在單獨的goroutine中進行的,處理一個request也可能設計多個goroutine之間的互動, 使用context可以使開發人員方便的在這些goroutine裡傳遞request相關的資料、取消goroutine的signal或到期日。

Context結構

// A Context carries a deadline, cancelation 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{}}

Done 方法在Context被取消或逾時時返回一個close的channel,close的channel可以作為廣播通知,告訴給context相關的函數要停止當前工作然後返回。

當一個父operation啟動一個goroutine用於子operation,這些子operation不能夠取消父operation。下面描述的WithCancel函數提供一種方式可以取消新建立的Context.

Context可以安全的被多個goroutine使用。開發人員可以把一個Context傳遞給任意多個goroutine然後cancel這個context的時候就能夠通知到所有的goroutine。

Err方法返回context為什麼被取消。

Deadline返回context何時會逾時。

Value返回context相關的資料。

繼承的Context

BackGround

// 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

BackGound是所有Context的root,不能夠被cancel。

WithCancel

// WithCancel returns a copy of parent whose Done channel is closed as soon as// parent.Done is closed or cancel is called.func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

WithCancel返回一個繼承的Context,這個Context在父Context的Done被關閉時關閉自己的Done通道,或者在自己被Cancel的時候關閉自己的Done。
WithCancel同時還返回一個取消函數cancel,這個cancel用於取消當前的Context。

視頻Advanced Go Concurrency Patterns中的第一個關於WithCancel的範例代碼,本人有所修改

package mainimport (    "context"    "log"    "os"    "time")var logg *log.Loggerfunc someHandler() {    ctx, cancel := context.WithCancel(context.Background())    go doStuff(ctx)//10秒後取消doStuff    time.Sleep(10 * time.Second)    cancel()}//每1秒work一下,同時會判斷ctx是否被取消了,如果是就退出func doStuff(ctx context.Context) {    for {        time.Sleep(1 * time.Second)        select {        case <-ctx.Done():            logg.Printf("done")            return        default:            logg.Printf("work")        }    }}func main() {    logg = log.New(os.Stdout, "", log.Ltime)    someHandler()    logg.Printf("down")}

結果

E:\wdy\goproject>go run context_learn.go15:06:44 work15:06:45 work15:06:46 work15:06:47 work15:06:48 work15:06:49 work15:06:50 work15:06:51 work15:06:52 work15:06:53 down

withDeadline withTimeout

WithTimeout func(parent Context, timeout time.Duration) (Context, CancelFunc)WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).

WithTimeout 等價於 WithDeadline(parent, time.Now().Add(timeout)).

對上面的範例代碼進行修改

func timeoutHandler() {    // ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)    ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))    // go doTimeOutStuff(ctx)    go doStuff(ctx)    time.Sleep(10 * time.Second)    cancel()}func main() {    logg = log.New(os.Stdout, "", log.Ltime)    timeoutHandler()    logg.Printf("end")}

輸出

15:59:22 work15:59:24 work15:59:25 work15:59:26 work15:59:27 done15:59:31 end

可以看到doStuff在context逾時的時候被取消了,ctx.Done()被關閉。
將context.WithDeadline替換為context.WithTimeout

func timeoutHandler() {    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)    // ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))    // go doTimeOutStuff(ctx)    go doStuff(ctx)    time.Sleep(10 * time.Second)    cancel()}

輸出

16:02:47 work16:02:49 work16:02:50 work16:02:51 work16:02:52 done16:02:56 end

根據視頻Advanced Go Concurrency Patterns5分48秒處的代碼編寫doTimeOutStuff替換doStuff

func doTimeOutStuff(ctx context.Context) {    for {        time.Sleep(1 * time.Second)        if deadline, ok := ctx.Deadline(); ok { //設定了deadl            logg.Printf("deadline set")            if time.Now().After(deadline) {                logg.Printf(ctx.Err().Error())                return            }        }        select {        case <-ctx.Done():            logg.Printf("done")            return        default:            logg.Printf("work")        }    }}func timeoutHandler() {    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)    // ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))    go doTimeOutStuff(ctx)    // go doStuff(ctx)    time.Sleep(10 * time.Second)    cancel()}

輸出:

16:03:55 deadline set16:03:55 work16:03:56 deadline set16:03:56 work16:03:57 deadline set16:03:57 work16:03:58 deadline set16:03:58 work16:03:59 deadline set16:03:59 context deadline exceeded16:04:04 end

context deadline exceeded就是ctx逾時的時候ctx.Err的錯誤訊息。

搜尋測試程式

完整代碼參見官方文檔Go Concurrency Patterns: Context,其中關鍵的地方在於函數httpDo

func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {    // Run the HTTP request in a goroutine and pass the response to f.    tr := &http.Transport{}    client := &http.Client{Transport: tr}    c := make(chan error, 1)    go func() { c <- f(client.Do(req)) }()    select {    case <-ctx.Done():        tr.CancelRequest(req)        <-c // Wait for f to return.        return ctx.Err()    case err := <-c:        return err    }}

httpDo關鍵的地方在於

    select {    case <-ctx.Done():        tr.CancelRequest(req)        <-c // Wait for f to return.        return ctx.Err()    case err := <-c:        return err    }

要麼ctx被取消,要麼request請求出錯。

WithValue

func WithValue(parent Context, key interface{}, val interface{}) Context

參見搜尋程式userip中的代碼
關鍵的代碼如下:

// NewContext returns a new Context carrying userIP.func NewContext(ctx context.Context, userIP net.IP) context.Context {    return context.WithValue(ctx, userIPKey, userIP)}// FromContext extracts the user IP address from ctx, if present.func FromContext(ctx context.Context) (net.IP, bool) {    // ctx.Value returns nil if ctx has no value for the key;    // the net.IP type assertion returns ok=false for nil.    userIP, ok := ctx.Value(userIPKey).(net.IP)    return userIP, ok}

go doc中的資訊

The WithCancel, WithDeadline, and WithTimeout functions take a Context (theparent) and return a derived Context (the child) and a CancelFunc. Callingthe CancelFunc cancels the child and its children, removes the parent'sreference to the child, and stops any associated timers.

裡面需要注意的就是 調用CancelFunc會取消child以及child產生的context,取出父context對這個child的引用,停止相關的計數器。

後記

之前一直在CSDN上寫文章,後面會逐步轉換到簡書上,還請大家多多支援。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.