1 context简介
标准库context,它定义了Context类型,专门用来简化 对于处理单个请求的多个 goroutine 之间与请求域的数据、取消信号、截止时间等相关操作,这些操作可能涉及多个 API 调用。
对服务器传入的请求应该创建上下文,而对服务器的传出调用应该接受上下文。它们之间的函数调用链必须传递上下文,或者可以使用WithCancel、WithDeadline、WithTimeout或WithValue创建的派生上下文。当一个上下文被取消时,它派生的所有上下文也被取消。
2 Context接口
context.Context是一个接口,该接口定义了四个需要实现的方法。
type Context interface {Deadline() (deadline time.Time, ok bool)Done() <-chan struct{}Err() errorValue(key interface{}) interface{}}
- Deadline()方法需要返回当前Context被取消的时间,也就是完成工作的截止时间(deadline);
- Done()方法需要返回一个Channel,这个Channel会在当前工作完成或者上下文被取消之后关闭,多次调用Done方法会返回同一个Channel;
- Err()方法会返回当前Context结束的原因,它只会在Done返回的Channel被关闭时才会返回非空的值;
- 如果当前Context被取消就会返回Canceled错误;
- 如果当前Context超时就会返回DeadlineExceeded错误;
Value方法会从Context中返回键对应的值,对于同一个上下文来说,多次调用Value 并传入相同的Key会返回相同的结果,该方法仅用于传递跨API和进程间跟请求域的数据;
3 Background()和TODO()
Go内置两个函数:Background()和TODO(),这两个函数分别返回一个实现了Context接口的background和todo。我们代码中最开始都是以这两个内置的上下文对象作为最顶层的partent context,衍生出更多的子上下文对象。
Background()主要用于main函数、初始化以及测试代码中,作为Context这个树结构的最顶层的Context,也就是根Context。
TODO(),它目前还不知道具体的使用场景,如果我们不知道该使用什么Context的时候,可以使用这个。4 with系列函数
(1) WithCancel
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
WithCancel返回带有新Done通道的父节点的副本。当调用返回的cancel函数或当关闭父上下文的Done通道时,将关闭返回上下文的Done通道,无论先发生什么情况。
func gen(ctx context.Context) <-chan int {dst := make(chan int)n := 1go func() {for {select {case <-ctx.Done():return // return结束该goroutine,防止泄露case dst <- n:n++}}}()return dst}func main() {ctx, cancel := context.WithCancel(context.Background())defer cancel() // 当我们取完需要的整数后调用cancelfor n := range gen(ctx) {fmt.Println(n)if n == 5 {break}}}
(2) WithDeadline
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
返回父上下文的副本,并将deadline调整为不迟于d。如果父上下文的deadline已经早于d,则WithDeadline(parent, d)在语义上等同于父上下文。当截止日过期时,当调用返回的cancel函数时,或者当父上下文的Done通道关闭时,返回上下文的Done通道将被关闭,以最先发生的情况为准。
取消此上下文将释放与其关联的资源,因此代码应该在此上下文中运行的操作完成后立即调用cancel。
func main() {d := time.Now().Add(50 * time.Millisecond)ctx, cancel := context.WithDeadline(context.Background(), d)// 尽管ctx会过期,但在任何情况下调用它的cancel函数都是很好的实践。// 如果不这样做,可能会使上下文及其父类存活的时间超过必要的时间。defer cancel()select {case <-time.After(1 * time.Second):fmt.Println("overslept")case <-ctx.Done():fmt.Println(ctx.Err())}}
上面的代码中,定义了一个50毫秒之后过期的deadline,然后我们调用context.WithDeadline(context.Background(), d)得到一个上下文(ctx)和一个取消函数(cancel),然后使用一个select让主程序陷入等待:等待1秒后打印overslept退出或者等待ctx过期后退出。 因为ctx50秒后就过期,所以ctx.Done()会先接收到值,上面的代码会打印ctx.Err()取消原因。
(3) WithTimeout
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithTimeout返回WithDeadline(parent, time.Now().Add(timeout))。
取消此上下文将释放与其相关的资源,因此代码应该在此上下文中运行的操作完成后立即调用cancel,通常用于数据库或者网络连接的超时控制。具体示例如下:
package mainimport ("context""fmt""sync""time")// context.WithTimeoutvar wg sync.WaitGroupfunc worker(ctx context.Context) {LOOP:for {fmt.Println("db connecting ...")time.Sleep(time.Millisecond * 10) // 假设正常连接数据库耗时10毫秒select {case <-ctx.Done(): // 50毫秒后自动调用break LOOPdefault:}}fmt.Println("worker done!")wg.Done()}func main() {// 设置一个50毫秒的超时ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)wg.Add(1)go worker(ctx)time.Sleep(time.Second * 5)cancel() // 通知子goroutine结束wg.Wait()fmt.Println("over")}
(4) WithValue
WithValue函数能够将请求作用域的数据与 Context 对象建立关系。
func WithValue(parent Context, key, val interface{}) Context
WithValue返回父节点的副本,其中与key关联的值为val。
仅对API和进程间传递请求域的数据使用上下文值,而不是使用它来传递可选参数给函数。
所提供的键必须是可比较的,并且不应该是string类型或任何其他内置类型,以避免使用上下文在包之间发生冲突。WithValue的用户应该为键定义自己的类型。为了避免在分配给interface{}时进行分配,上下文键通常具有具体类型struct{}。或者,导出的上下文关键变量的静态类型应该是指针或接口。
package mainimport ("context""fmt""sync""time")// context.WithValuetype TraceCode stringvar wg sync.WaitGroupfunc worker(ctx context.Context) {key := TraceCode("TRACE_CODE")traceCode, ok := ctx.Value(key).(string) // 在子goroutine中获取trace codeif !ok {fmt.Println("invalid trace code")}LOOP:for {fmt.Printf("worker, trace code:%s\n", traceCode)time.Sleep(time.Millisecond * 10) // 假设正常连接数据库耗时10毫秒select {case <-ctx.Done(): // 50毫秒后自动调用break LOOPdefault:}}fmt.Println("worker done!")wg.Done()}func main() {// 设置一个50毫秒的超时ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)// 在系统的入口中设置trace code传递给后续启动的goroutine实现日志数据聚合ctx = context.WithValue(ctx, TraceCode("TRACE_CODE"), "12512312234")wg.Add(1)go worker(ctx)time.Sleep(time.Second * 5)cancel() // 通知子goroutine结束wg.Wait()fmt.Println("over")}
5 案例: 客户端超时取消请求
(1) server
package mainimport ("fmt""math/rand""net/http""time")// server端,随机出现慢响应func indexHandler(w http.ResponseWriter, r *http.Request) {number := rand.Intn(2)if number == 0 {time.Sleep(time.Second * 10) // 耗时10秒的慢响应fmt.Fprintf(w, "slow response")return}fmt.Fprint(w, "quick response")}func main() {http.HandleFunc("/", indexHandler)err := http.ListenAndServe(":8000", nil)if err != nil {panic(err)}}
(2) client
package mainimport ("context""fmt""io/ioutil""net/http""sync""time")type respData struct {resp *http.Responseerr error}func doCall(ctx context.Context) {transport := http.Transport{DisableKeepAlives: true, // 请求不频繁使用短链接}client := http.Client{Transport: &transport,}req, err := http.NewRequest("GET", "http://127.0.0.1:8000/", nil)if err != nil {fmt.Printf("new requestg failed, err:%v\n", err)return}req = req.WithContext(ctx) // 使用带超时的ctx创建一个新的client requestvar wg sync.WaitGroupwg.Add(1)defer wg.Wait()respChan := make(chan *respData, 1)go func() {resp, err := client.Do(req)fmt.Printf("client.do resp:%v, err:%v\n", resp, err)rd := &respData{resp: resp,err: err,}respChan <- rdwg.Done()}()select {case <-ctx.Done():fmt.Println("call api timeout")case result := <-respChan:fmt.Println("call server api success")if result.err != nil {fmt.Printf("call server api failed, err:%v\n", result.err)return}defer result.resp.Body.Close()data, _ := ioutil.ReadAll(result.resp.Body)fmt.Printf("resp:%v\n", string(data))}}func main() {// 定义一个100毫秒的超时ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*100)defer cancel() // 调用cancel释放子goroutine资源doCall(ctx)}
6 案例: 优雅退出子go程
在Go中, 不能直接杀死协程,
协程的关闭, 一般采用channel和select的方式来控制
但在某些场景下, 一个请求可能会开启多个协程, 它们需要被同时关闭
这样用channel和select就比较难实现, 而context就可以解决这个问题
(1) 关闭单个协程
package mainimport ("context""fmt""time")func doWork(ctx context.Context) {ch := make(chan int) // 这个用来放返回值// 真正的逻辑要放到一个go程里去做go func() {for i := 0; i < 100; i++ {fmt.Println("do work")if i == 1 { // 调整这个值看效果ch <- 5break}time.Sleep(time.Second * 1)}fmt.Println("work done")}()select {case <-ctx.Done():fmt.Println("cancel")case i := <-ch:fmt.Println("return", i)}}func main() {ctx, cancel := context.WithCancel(context.Background())go doWork(ctx)fmt.Println("开始")time.Sleep(time.Second * 2)fmt.Println("正在取消")cancel()fmt.Println("取消完成")time.Sleep(time.Second * 2)fmt.Println("结束")}
输出结果为:
开始 do work do work work done get 5 正在取消 取消完成 结束
(2) 关闭多个协程
package mainimport ("context""fmt""sync""time")var wg sync.WaitGroup// 可以把 接收取消通知 这部分封装一下, 更容易理解func isCancel(ctx context.Context) bool {select {case <-ctx.Done(): // 接收取消通知return truedefault:return false}}func worker(ctx context.Context) {go worker2(ctx)for {fmt.Println("worker")time.Sleep(time.Second)if isCancel(ctx) {break}}wg.Done()}func worker2(ctx context.Context) {for {fmt.Println("worker2")time.Sleep(time.Second)if isCancel(ctx) {break}}}func main() {ctx, cancel := context.WithCancel(context.Background())wg.Add(1)go worker(ctx)time.Sleep(time.Second * 3)cancel() // 通知子goroutine结束wg.Wait()fmt.Println("over")}
