欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

深入Golang之context的用法詳解

 更新時(shí)間:2018年03月23日 10:14:28   作者:jasper的技術(shù)小窩  
本篇文章主要介紹了深入Golang之context的用法詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

context在Golang的1.7版本之前,是在包golang.org/x/net/context中的,但是后來發(fā)現(xiàn)其在很多地方都是需要用到的,所有在1.7開始被列入了Golang的標(biāo)準(zhǔn)庫。Context包專門用來簡化處理單個(gè)請求的多個(gè)goroutine之間與請求域的數(shù)據(jù)、取消信號、截止時(shí)間等相關(guān)操作,那么這篇文章就來看看其用法和實(shí)現(xiàn)原理。

源碼分析

首先我們來看一下Context里面核心的幾個(gè)數(shù)據(jù)結(jié)構(gòu):

Context interface

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

Deadline返回一個(gè)time.Time,是當(dāng)前Context的應(yīng)該結(jié)束的時(shí)間,ok表示是否有deadline。

Done方法在Context被取消或超時(shí)時(shí)返回一個(gè)close的channel,close的channel可以作為廣播通知,告訴給context相關(guān)的函數(shù)要停止當(dāng)前工作然后返回。

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

Value可以讓Goroutine共享一些數(shù)據(jù),當(dāng)然獲得數(shù)據(jù)是協(xié)程安全的。但使用這些數(shù)據(jù)的時(shí)候要注意同步,比如返回了一個(gè)map,而這個(gè)map的讀寫則要加鎖。

canceler interface

canceler interface定義了提供cancel函數(shù)的context:

type canceler interface {
  cancel(removeFromParent bool, err error)
  Done() <-chan struct{}
}

其現(xiàn)成的實(shí)現(xiàn)有4個(gè):

  1. emptyCtx:空的Context,只實(shí)現(xiàn)了Context interface;
  2. cancelCtx:繼承自Context并實(shí)現(xiàn)了cancelerinterface
  3. timerCtx:繼承自cancelCtx,可以用來設(shè)置timeout;
  4. valueCtx:可以儲存一對鍵值對;

繼承Context

context包提供了一些函數(shù),協(xié)助用戶從現(xiàn)有的 Context 對象創(chuàng)建新的 Context 對象。這些Context對象形成一棵樹:當(dāng)一個(gè) Context對象被取消時(shí),繼承自它的所有Context都會被取消。

Background是所有Context對象樹的根,它不能被取消,它是一個(gè)emptyCtx的實(shí)例:

var (
  background = new(emptyCtx)
)

func Background() Context {
  return background
}

生成Context的主要方法

WithCancel

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  c := newCancelCtx(parent)
  propagateCancel(parent, &c)
  return &c, func() { c.cancel(true, Canceled) }
}

返回一個(gè)cancelCtx示例,并返回一個(gè)函數(shù),可以在外層直接調(diào)用cancelCtx.cancel()來取消Context。

WithDeadline

func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
  if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
    return WithCancel(parent)
  }
  c := &timerCtx{
    cancelCtx: newCancelCtx(parent),
    deadline: deadline,
  }
  propagateCancel(parent, c)
  d := time.Until(deadline)
  if d <= 0 {
    c.cancel(true, DeadlineExceeded) // deadline has already passed
    return c, func() { c.cancel(true, Canceled) }
  }
  c.mu.Lock()
  defer c.mu.Unlock()
  if c.err == nil {
    c.timer = time.AfterFunc(d, func() {
      c.cancel(true, DeadlineExceeded)
    })
  }
  return c, func() { c.cancel(true, Canceled) }
}

返回一個(gè)timerCtx示例,設(shè)置具體的deadline時(shí)間,到達(dá) deadline的時(shí)候,后代goroutine退出。

WithTimeout

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  return WithDeadline(parent, time.Now().Add(timeout))
}

和WithDeadline一樣返回一個(gè)timerCtx示例,實(shí)際上就是WithDeadline包了一層,直接傳入時(shí)間的持續(xù)時(shí)間,結(jié)束后退出。

WithValue

func WithValue(parent Context, key, val interface{}) Context {
  if key == nil {
    panic("nil key")
  }
  if !reflect.TypeOf(key).Comparable() {
    panic("key is not comparable")
  }
  return &valueCtx{parent, key, val}
}

WithValue對應(yīng)valueCtx ,WithValue是在Context中設(shè)置一個(gè) map,這個(gè)Context以及它的后代的goroutine都可以拿到map 里的值。

例子

Context的使用最多的地方就是在Golang的web開發(fā)中,在http包的Server中,每一個(gè)請求在都有一個(gè)對應(yīng)的goroutine去處理。請求處理函數(shù)通常會啟動額外的goroutine用來訪問后端服務(wù),比如數(shù)據(jù)庫和RPC服務(wù)。用來處理一個(gè)請求的goroutine通常需要訪問一些與請求特定的數(shù)據(jù),比如終端用戶的身份認(rèn)證信息、驗(yàn)證相關(guān)的token、請求的截止時(shí)間。 當(dāng)一個(gè)請求被取消或超時(shí)時(shí),所有用來處理該請求的 goroutine都應(yīng)該迅速退出,然后系統(tǒng)才能釋放這些goroutine占用的資源。雖然我們不能從外部殺死某個(gè)goroutine,所以我就得讓它自己結(jié)束,之前我們用channel+select的方式,來解決這個(gè)問題,但是有些場景實(shí)現(xiàn)起來比較麻煩,例如由一個(gè)請求衍生出的各個(gè) goroutine之間需要滿足一定的約束關(guān)系,以實(shí)現(xiàn)一些諸如有效期,中止goroutine樹,傳遞請求全局變量之類的功能。

保存上下文

func middleWare(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    ctx := context.WithValue(req.Context(),"key","value")
    next.ServeHTTP(w, req.WithContext(ctx))
  })
}

func handler(w http.ResponseWriter, req *http.Request) {
  value := req.Context().Value("value").(string)
  fmt.Fprintln(w, "value: ", value)
  return
}

func main() {
  http.Handle("/", middleWare(http.HandlerFunc(handler)))
  http.ListenAndServe(":8080", nil)
}

我們可以在上下文中保存任何的類型的數(shù)據(jù),用于在整個(gè)請求的生命周期去傳遞使用。

超時(shí)控制

func longRunningCalculation(timeCost int)chan string{
  result:=make(chan string)
  go func (){
  time.Sleep(time.Second*(time.Duration(timeCost)))
    result<-"Done"
  }()
  return result
}

func jobWithTimeoutHandler(w http.ResponseWriter, r * http.Request){
  ctx,cancel := context.WithTimeout(context.Background(), 3*time.Second)
  defer cancel()

  select{
  case <-ctx.Done():
    log.Println(ctx.Err())
    return
  case result:=<-longRunningCalculation(5):
    io.WriteString(w,result)
  }
  return
}


func main() {
  http.Handle("/", jobWithTimeoutHandler)
  http.ListenAndServe(":8080", nil)
}

這里用一個(gè)timerCtx來控制一個(gè)函數(shù)的執(zhí)行時(shí)間,如果超過了這個(gè)時(shí)間,就會被迫中斷,這樣就可以控制一些時(shí)間比較長的操作,例如io,RPC調(diào)用等等。

除此之外,還有一個(gè)重要的就是cancelCtx的實(shí)例用法,可以在多個(gè)goroutine里面使用,這樣可以實(shí)現(xiàn)信號的廣播功能,具體的例子我這里就不再細(xì)說了。

總結(jié)

context包通過構(gòu)建樹型關(guān)系的Context,來達(dá)到上一層Goroutine能對傳遞給下一層Goroutine的控制??梢詡鬟f一些變量來共享,可以控制超時(shí),還可以控制多個(gè)Goroutine的退出。

據(jù)說在Google,要求Golang程序員把Context作為第一個(gè)參數(shù)傳遞給入口請求和出口請求鏈路上的每一個(gè)函數(shù)。這樣一方面保證了多個(gè)團(tuán)隊(duì)開發(fā)的Golang項(xiàng)目能夠良好地協(xié)作,另一方面它是一種簡單的超時(shí)和取消機(jī)制,保證了臨界區(qū)數(shù)據(jù)在不同的Golang項(xiàng)目中順利傳遞。

所以善于使用context,對于Golang的開發(fā),特別是web開發(fā),是大有裨益的。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論