context 上下文管理

context 翻译过来就是上下文管理,主要作用有两个:

  • 控制 goroutine 的超时
  • 保存上下文数据

WithTimeout

通过下面的一个简单的 http 例子进行理解

demo:

package main

import (
"fmt"
"time"
"net/http"
"context"
"io/ioutil"
) type Result struct{
r *http.Response
err error
} func process(){
ctx,cancel := context.WithTimeout(context.Background(),2*time.Second)
defer cancel()
tr := &http.Transport{}
client := &http.Client{Transport:tr}
c := make(chan Result,1)
req,err := http.NewRequest("GET","http://www.google.com",nil)
if err != nil{
fmt.Println("http request failed,err:",err)
return
}
// 如果请求成功了会将数据存入到管道中
go func(){
resp,err := client.Do(req)
pack := Result{resp,err}
c <- pack
}() select{
case <- ctx.Done():
tr.CancelRequest(req)
fmt.Println("timeout!")
case res := <-c:
defer res.r.Body.Close()
out,_:= ioutil.ReadAll(res.r.Body)
fmt.Printf("server response:%s",out)
}
return } func main() {
process()
}

WithValue

再写一个 context 保存上下文

demo:

package main

import (
"context"
"fmt"
) func add(ctx context.Context,a,b int) int {
traceId := ctx.Value("trace_id").(string)
fmt.Printf("trace_id:%v\n",traceId)
return a+b
} func calc(ctx context.Context,a, b int) int{
traceId := ctx.Value("trace_id").(string)
fmt.Printf("trace_id:%v\n",traceId)
//再将ctx传入到add中
return add(ctx,a,b)
} func main() {
//将ctx传递到calc中
ctx := context.WithValue(context.Background(),"trace_id","123456")
ret := calc(ctx,20,30)
fmt.Printf("%d", ret)
}

运行结果:

trace_id:123456
trace_id:123456
50

WithCancel 

关于 context 官网上也有一个例子非常有用,用来控制开启的 goroutine 的退出释放

demo:

package main

import (
"context"
"fmt"
) func main() {
// gen generates integers in a separate goroutine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal goroutine started by gen.
gen := func(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
return // returning not to leak the goroutine
case dst <- n:
n++
}
}
}()
return dst
} ctx, cancel := context.WithCancel(context.Background())
defer cancel() // cancel when we are finished consuming integers for n := range gen(ctx) {
fmt.Println(n)
if n == 5 {
break
}
}
}

WithDeadline

关于官网中的 WithDeadline 演示的代码例子

demo:

package main
import (
"context"
"fmt"
"time"
) func main() {
d := time.Now().Add(50 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), d) // Even though ctx will be expired, it is good practice to call its
// cancelation function in any case. Failure to do so may keep the
// context and its parent alive longer than necessary.
defer cancel() select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err())
} }

运行结果:

context deadline exceeded

ending ~

Go context 介绍和使用的更多相关文章

  1. Golang的Context介绍及其源码分析

    简介 在Go服务中,对于每个请求,都会起一个协程去处理.在处理协程中,也会起很多协程去访问资源,比如数据库,比如RPC,这些协程还需要访问请求维度的一些信息比如说请求方的身份,授权信息等等.当一个请求 ...

  2. Tomcat下server.xml中context介绍

    conf/Context.xml是Tomcat公用的环境配置;若在server.xml中增加<Context path="/test" docBase="D:\te ...

  3. Android Context介绍

    转载(Android Context完全解析与各种获取Context方法):https://www.cnblogs.com/chenxibobo/p/6136693.html

  4. 理解Go Context机制

    1 什么是Context 最近在公司分析gRPC源码,proto文件生成的代码,接口函数第一个参数统一是ctx context.Context接口,公司不少同事都不了解这样设计的出发点是什么,其实我也 ...

  5. Android上下文Context

    Android上下文Context介绍 在应用开发中最熟悉而陌生的朋友-----Context类 ,说它熟悉,是应为我们在开发中时刻的在与它打交道,例如:Service.BroadcastReceiv ...

  6. Golang 高效实践之并发实践context篇

    前言 在上篇Golang高效实践之并发实践channel篇中我给大家介绍了Golang并发模型,详细的介绍了channel的用法,和用select管理channel.比如说我们可以用channel来控 ...

  7. Go实现海量日志收集系统(三)

    再次整理了一下这个日志收集系统的框,如下图 这次要实现的代码的整体逻辑为: 完整代码地址为: https://github.com/pythonsite/logagent etcd介绍 高可用的分布式 ...

  8. Flask类的属性和方法大全

    Flask Property__class____dict____doc____module__app_ctx_globals_classconfig_classdebugdefault_config ...

  9. OpenGL Windows 窗口程序环境搭建

    OpenGL环境搭建步骤: Downloading OpenGL 根据官网的说法: In all three major desktop platforms (Linux, macOS, and Wi ...

随机推荐

  1. Visual Studio 2019更新到16.2.2

    Visual Studio 2019更新到16.2.2 此次更新的变化有以下几点: (1)修复了Visual Studio在关闭时的停止响应问题.(2)修复CVE-2019-1211权限提升漏洞.(3 ...

  2. [原][bigemap][globalmapper]通过bigemap下载全球30米DEM高程数据(手动下载)(下载全球高精度dom卫片、影像、等高线、矢量路网、POI、行政边界)

    本文研究了bigemap下载高程数据的方式,但是严重不推荐使用这总手动方式,bigemap这个软件一次只能下载100M以内的高程数据,即使花钱,也不给你提供批量下载dem的方式!也有些其他更好的软件, ...

  3. TypeScript泛型类 - 把类作为参数类型的泛型类

    /* TypeScript泛型类 - 把类作为参数类型的泛型类 */ /* 泛类:泛型可以帮助我们避免重复的代码以及对不特定数据类型的支持(类型校验),下面我们看看把类当做参数的泛型类 1.定义个类 ...

  4. java输出一个目录下的子目录

    java输出一个目录下的子目录 package com.vfsd.core; import java.io.File; public class ListDir { public static voi ...

  5. ubuntu 防火墙打开关闭

    1.查看防火墙状态 sudo ufw status 2.打开防火墙 sudo ufw enable 3.关闭防火墙 sudo ufw disable

  6. array_fill 填充数组内容

    <?php $a = array_fill(, , 'banana'); $b = array_fill(-, , 'pear'); print_r($a); print_r($b) Array ...

  7. 打乱数组 shuffle

    <?php $arr = range(,); print_r($arr); echo '<br />'; shuffle($arr); print_r($arr); ?> Ar ...

  8. JS获当前网页元素高度offsetHeight

    本文测试的是offsetHeight,获取网页中某元素的高度,单位是像素,获取的类型是整型,可以进行数字运算.如图,网页中的元素本身的高度包括,自身的内容+padding+border,而margin ...

  9. easyui前台改变datagrid某单元格的值

    有时候前台完成某个操作后要修改datagrid的值, 也许这个datagrid是没有保存的, 所以要修改后才能传递到后台; 也许要其他操作过后才需请求后台; 这些情况都需要前台对datagrid的单元 ...

  10. Tools - Summary List

    通用 PicPick:https://picpick.app/zh/ Q-Dir:http://www.softwareok.com/?Download=Q-Dir 7-Zip:https://www ...