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 ...
随机推荐
- 算法习题---5-2Ducci序列(UVa1594)
一:题目 对于一个n元组(a1, a2, …, an),可以对于每个数求出它和下一个数的差的绝对值,得到一个新的n元组(|a1-a2|, |a2-a3|, …, |an-a1|).重复这个过程,得到的 ...
- Linux的桌面虚拟化技术KVM(一)——新建KVM虚拟机
(1).虚拟化产品对比介绍 虚拟化技术有以下三种:仿真虚拟化,这是一种对系统硬件没有要求,但性能最低的虚拟化技术:半虚拟化,这是一种直接使用物理硬件,性能高,但需要修改内核的虚拟化技术:全虚拟化,这是 ...
- LwIP应用开发笔记之一:LwIP无操作系统基本移植
现在,TCP/IP协议的应用无处不在.随着物联网的火爆,嵌入式领域使用TCP/IP协议进行通讯也越来越广泛.在我们的相关产品中,也都有应用,所以我们结合应用实际对相关应用作相应的总结. 1.技术准备 ...
- html div高度100%无效
移动端相关: div高度继承自父元素——>body——>html 解决方案: html,body { height: 100%;margin: 0; padding: 0;} 然后对应的d ...
- Django:ORM中ForeignKey外键关系分析
假设有两张表,Role和User,因为多个用户会对应一个角色,属于多对一关系,所以User中的rolename字段使用ForeignKey,第一个参数为要关联的表Role,第二个参数related_n ...
- 【译】Vue源码学习(一):Vue对象构造函数
本系列文章详细深入Vue.js的源代码,以此来说明JavaScript的基本概念,尝试将这些概念分解到JavaScript初学者可以理解的水平.有关本系列的一些后续的计划和轨迹的更多信息,请参阅此文章 ...
- 高级UI-SVG
栅格图可以实现图片的清晰显示,但这也意味着如果要在各种设备上使用栅格图,那么在使用的时候就会产生为了适配各种尺寸的设备而增加大量不同规格的栅格图,这也直接导致了资源文件体积的增大,矢量图就不存在这个问 ...
- 探索typescript的必经之路-----接口(interface)
TypeScript定义接口 熟悉编程语言的同学都知道,接口(interface)的重要性不言而喻. 很多内容都会运用到接口.typescrip中的接口类似于java,同时还增加了更灵活的接口类型,包 ...
- [转帖]TPC-C解析系列04_TPC-C基准测试之数据库事务引擎的挑战
TPC-C解析系列04_TPC-C基准测试之数据库事务引擎的挑战 http://www.itpub.net/2019/10/08/3331/ OceanBase这次TPC-C测试与榜单上Oracl ...
- Fiddler使其在HttpURLConnection下正常抓包
像陌陌这样使用HttpURLConnection进行通讯的APP还是无能为力 还需要对fiddler进行如下设置: 点击"Rules->CustomizeRules"; 在这 ...