Go context 介绍和使用
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 介绍和使用的更多相关文章
- Golang的Context介绍及其源码分析
简介 在Go服务中,对于每个请求,都会起一个协程去处理.在处理协程中,也会起很多协程去访问资源,比如数据库,比如RPC,这些协程还需要访问请求维度的一些信息比如说请求方的身份,授权信息等等.当一个请求 ...
- Tomcat下server.xml中context介绍
conf/Context.xml是Tomcat公用的环境配置;若在server.xml中增加<Context path="/test" docBase="D:\te ...
- Android Context介绍
转载(Android Context完全解析与各种获取Context方法):https://www.cnblogs.com/chenxibobo/p/6136693.html
- 理解Go Context机制
1 什么是Context 最近在公司分析gRPC源码,proto文件生成的代码,接口函数第一个参数统一是ctx context.Context接口,公司不少同事都不了解这样设计的出发点是什么,其实我也 ...
- Android上下文Context
Android上下文Context介绍 在应用开发中最熟悉而陌生的朋友-----Context类 ,说它熟悉,是应为我们在开发中时刻的在与它打交道,例如:Service.BroadcastReceiv ...
- Golang 高效实践之并发实践context篇
前言 在上篇Golang高效实践之并发实践channel篇中我给大家介绍了Golang并发模型,详细的介绍了channel的用法,和用select管理channel.比如说我们可以用channel来控 ...
- Go实现海量日志收集系统(三)
再次整理了一下这个日志收集系统的框,如下图 这次要实现的代码的整体逻辑为: 完整代码地址为: https://github.com/pythonsite/logagent etcd介绍 高可用的分布式 ...
- Flask类的属性和方法大全
Flask Property__class____dict____doc____module__app_ctx_globals_classconfig_classdebugdefault_config ...
- OpenGL Windows 窗口程序环境搭建
OpenGL环境搭建步骤: Downloading OpenGL 根据官网的说法: In all three major desktop platforms (Linux, macOS, and Wi ...
随机推荐
- jenkins发布程序触发shell调用python脚本刷新akamai cdn api
刷新cdn的流程:jenkins获取git中的代码,触发脚本推送到生产环境中(即cdn的源站) --> 触发脚本获取git工作目录的更新列表,将更新列表拼凑成带域名信息的url,写入到目录中 - ...
- OMPL RRTConnet 生成路径和可视化
默认规划路径算法和RRTConnet路径规划算法生成路径 1. 源代码 #include <ompl/base/SpaceInformation.h> #include <ompl ...
- 算法习题---5-2Ducci序列(UVa1594)
一:题目 对于一个n元组(a1, a2, …, an),可以对于每个数求出它和下一个数的差的绝对值,得到一个新的n元组(|a1-a2|, |a2-a3|, …, |an-a1|).重复这个过程,得到的 ...
- Python中random模块生成随机数详解
Python中random模块生成随机数详解 本文给大家汇总了一下在Python中random模块中最常用的生成随机数的方法,有需要的小伙伴可以参考下 Python中的random模块用于生成随机数. ...
- Nginx - upstream sent invalid chunked response while reading upstream 异常问题
一个 post 的请求,直接调接口服务数据正常返回,但是通过 nginx 代理后, 什么都没有返回. nginx 配置如下: 使用 postman 调用,返回如下: 于是检查日志报错信息,如下: ng ...
- css样式writing-mode垂直书写测试
writing-mode:控制文字的属性方向,但是不是所有的浏览器都兼容,在网页上使用时,有的浏览器显示不出该样式.该文测试的是垂直书写:网上对于测试的属性值的解释是:tb-rl:上-下,右-左.对象 ...
- SUBLIME必备插件FOR PHP
Sublime Text真是一款写代码的利器,轻巧快捷,而且功能强大,用来写PHP代码再好不过了,告别以前用的笨重臃肿的Zend Studio,感觉一身轻松,PHP代码也更加优雅.但是PHP开发也经常 ...
- 记录 centos samba 安装
https://www.ruletree.club/archives/4/ https://www.linuxidc.com/Linux/2017-03/141390.htm
- 高级UI-沉浸式设计
关于沉浸式设计,在国内指的是Toolbar和系统状态栏相统一,而谷歌官方给出的沉浸式则是指整个界面为UI所用,而这里所说的沉浸式则是指的前者,涉及4.4和5.0及以上,4.4以下的Android做不出 ...
- 高性能最终一致性框架Ray之基本功能篇
一.Event(事件) Event是Actor产生的记录状态变化的日志,由StateId(状态Id),UID(幂等性控制),TypeCode(事件类型),Data(事件数据),Version(事件版本 ...