在go服务中,对于每个请求,都会起一个协程去处理。在处理协程中,也会起很多协程去访问资源,比如数据库,比如rpc,这些协程还需要访问请求维度的一些信息比如说请求方的身份,授权信息等等。当一个请求被取消或者超时的时候,其他所有协程都应该立即被取消以释放资源。
golang的context包就是用来传递请求维度的数据、信号、超时给处理该请求的所有协程的。在处理请求的方法调用链中,必须传递context,当然也可以使用withcancel, withdeadline, withtimeout或者withvalue去派生出子context来传递。当一个context被取消的时候,其派生出的所有子context都会被取消。
包的介绍
在context包中,最核心的就是context接口,其结构如下:
type context interface { deadline() (deadline time.time, ok bool) done() <-chan struct{} err() error value(key interface{}) interface{} }
一个context可以传递一个截止时间、一个取消信号和其他值。其方法是可以被多个协程同时调用的。
deadline() (deadline time.time, ok bool)
返回一个截止时间,代表这个context要到达截止时间会被取消。返回的ok如果是false表示没有设置截止时间,即不会超时。
done() <-chan struct{}
返回一个已经关闭的channel,表示这个context被取消了。如果这个context永远不能被取消的话,则返回nil。
一般done的放在select语句中使用,如:
func stream(ctx context.context, out chan<- value) error {//stream函数就是用来不断产生值并把值发送到out channel里,直到发生dosomething发生错误或者ctx.done关闭 for { v, err := dosomething(ctx)//dosomething用来产生值 if err != nil { return err } select { case <-ctx.done(): //ctx.done关闭 return ctx.err() case out <- v://将产生的值发送出去 } } }
var canceled = errors.new("context canceled") var deadlineexceeded error = deadlineexceedederror{}
func withcancel(parent context) (ctx context, cancel cancelfunc)
拷贝父context,并赋予一个新的done channel。返回这个context以及cancel函数。
当以下情况发生其中之一时,这个context会被取消:
func main() { //gen函数用来产生一个不断生产数字到channel的协程,并返回channel gen := func(ctx context.context) <-chan int { dst := make(chan int) n := 1 go func() { for { select { case <-ctx.done(): return //每一次生产数字都检查context是否已经被取消,防止协程泄露 case dst <- n: n++ } } }() return dst } ctx, cancel := context.withcancel(context.background()) defer cancel() //在消费完生产的数字之后,调用cancel函数来取消context,以此通知其他协程 for n := range gen(ctx) { //只消费5个数字 fmt.println(n) if n == 5 { break } } }
这个方法是怎么实现的呢?让我们来看一下源码:
func withcancel(parent context) (ctx context, cancel cancelfunc) { c := newcancelctx(parent) propagatecancel(parent, &c) return &c, func() { c.cancel(true, canceled) } }
可以看到主要是两个方法:newcancelctx和propagatecancel
newcancelctx是用父context初始化一个cancelctx对象,cancelctx是context的一个实现类:
func newcancelctx(parent context) cancelctx { return cancelctx{context: parent} }
看下这个newcancelctx的结构,newcancelctx其实是context接口的一个实现类:
type cancelctx struct { context //指向父context的引用 mu sync.mutex // 锁用来保护下面几个字段 done chan struct{} // 用来通知其他,代表这个context已经结束了 children map[canceler]struct{} // 里面保存了所有子contex的联系,用来在结束当前context的时候,结束所有子context。这个字段cancel之后,设为nil。 err error // cancel之后,就不是nil了。 }
propagatecancel顾名思义,就是传播cancel,就是保证父context结束的时候,我们用withcancel得到的子context能够跟着结束。
然后返回这个新建的cancelctx对象和一个cancelfunc。cancelfunc是一个函数,内部是调用了cancelctx对象的cancel方法,这个方法的作用是关闭cancelctx对象的done channel(代表这个context结束了),然后cancel这个context的所有子context,如果必要的话并切断这个context和其父context的关系(其实就是这个context的子context通过propagatecancel关联上的)。
看下propagatecancel的内部:
func propagatecancel(parent context, child canceler) { if parent.done() == nil {//父context如果永远不能取消,直接返回,不用关联。 return } if p, ok := parentcancelctx(parent); ok {//因为传入的父context类型是context接口,不一定是cancelctx,所以如果要关联,则先判断类型 p.mu.lock()//加锁,保护字段children if p.err != nil {//说明父context已经结束了,也别做其他操作了,直接取消这个子context吧 child.cancel(false, p.err) } else {//没有结束,就在父context里加上子context的联系,用来之后取消子context用 if p.children == nil { p.children = make(map[canceler]struct{}) } p.children[child] = struct{}{} } p.mu.unlock() } else {//因为传入的父context类型不是cancelctx,则不一定有children字段的,只能起一个协程来监听父context的done,如果done关闭了,就可以取消子context了。 go func() { select { case <-parent.done(): child.cancel(false, parent.err()) case <-child.done()://为了避免子context比父context先取消,造成这个监听协程泄露,这里加了这样一个case } }() } }
再来看一下,withcancel的return &c, func() { c.cancel(true, canceled) }中的c.cancel(true, canceled)到底干了啥:
因为c是类型cancelctx,其有一个方法是cancel,这个方法其实是实现的cancel接口的方法,这在前面的cancelctx的字段children map[canceler]struct{}中,可以看到这个map的key就是这个接口。
type canceler interface { cancel(removefromparent bool, err error) done() <-chan struct{} }
这个接口包含了两个方法,实现类有*cancelctx 和*timerctx。
看下*cancelctx的实现,这个方法的作用是关闭cancelctx对象的done channel(代表这个context结束了),然后cancel这个context的所有子context,如果必要的话并切断这个context和其父context的关系(其实就是这个context的子context通过propagatecancel关联上的):
func (c *cancelctx) cancel(removefromparent bool, err error) { if err == nil {//任何context关闭后,都需要一个错误来给字段err赋值来表明结束的原因,不传入err是不行的 panic("context: internal error: missing cancel error") } c.mu.lock()//加锁 if c.err != nil {//如果错误已经有了,说明这个context已经结束了,就不用cancel了 c.mu.unlock() return // already canceled } c.err = err//赋值错误原因 if c.done == nil { c.done = closedchan //这个字段延迟加载,closedchan是一个context包中的量,一个已经关闭的channel,所有context都复用这个关闭的channel } else {//当然如果已经加载了,则直接关闭。那是啥时候加载的呢?当然是在这个context还没结束的时候,有人调用了done()方法,所以是延迟加载。 close(c.done) } for child := range c.children {//结束所有子context。之前每次的propagatecancel总算派上用场了。 child.cancel(false, err) } c.children = nil c.mu.unlock() if removefromparent {//如果需要的话,切断当前context和父context的联系。就是从父context的children map里移除嘛。当然如果fucontext不是cancelctx,就没事咯 removechild(c.context, c) } }
这样就介绍完源码了,看起来不错哦。
func withdeadline(parent context, d time.time) (context, cancelfunc)
拷贝父context,并设置截止时间为d。如果父context截止时间小于d,则使用父context的截止时间。
当以下情况发生其中之一时,这个context会被取消:
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()) } }
看一下withdeadline的实现是怎么样的:
func withdeadline(parent context, d time.time) (context, cancelfunc) { if cur, ok := parent.deadline(); ok && cur.before(d) {//如果当前的deadline比父deadline晚,则用父deadline,直接withcancel就好了,因为父deadline到了结束了,这个context也就结束了。withcancel是为了返回一个cancelfunc。 return withcancel(parent) } c := &timerctx{//可以看到,timerctx其实就是包装了一下newcancelctx,newcancelctx在前文已经介绍了,这里看上去就简单多了。 cancelctx: newcancelctx(parent), deadline: d, } propagatecancel(parent, c)//propagatecancel在前文介绍过了,这里就是传播cancel嘛。 dur := time.until(d) if dur <= 0 {//时间到了,就直接可以cancel了 c.cancel(true, deadlineexceeded) return c, func() { c.cancel(false, canceled) } } c.mu.lock() defer c.mu.unlock() if c.err == nil {//如果还没取消,就设置个定时器,afterfunc函数就是说,在时间dur之后,执行func,即cancel。 c.timer = time.afterfunc(dur, func() { c.cancel(true, deadlineexceeded) }) } return c, func() { c.cancel(true, canceled) } }
理解了withcancel的实现,这个withcancel的源码还是很简单的。
func withtimeout(parent context, timeout time.duration) (context, cancelfunc)
一定时间后超时,自动取消context以及其子context。
其实就是用了withdeadline,只不过截止日期写的是当前时间+timeout
func withtimeout(parent context, timeout time.duration) (context, cancelfunc) { return withdeadline(parent, time.now().add(timeout)) }
使用示例是一样的
func main() { ctx, cancel := context.withtimeout(context.background(), 50*time.millisecond) defer cancel() select { case <-time.after(1 * time.second): fmt.println("overslept") case <-ctx.done(): fmt.println(ctx.err()) } }
看withdeadline的源码就好。
func withvalue(parent context, key, val interface{}) context
拷贝父context,并在context中设置键值。这样就可以从context中取出数据来使用。
需要注意的是,用context 的value来传递请求维度的数据,不要用来传递函数的可选参数。
传递数据使用的key,不应该是string或者其他任何go的内置类型,而是应该使用用户自定义的类型作为key。这样能避免冲突。
key必须是可比较的,意思是可以用来判断是否是同一个key,即相等。
导出的context key的静态类型应该用指针或者interface
使用示例
func main() { type favcontextkey string //定义一个自定义类型作为key f := func(ctx context.context, k interface{}) {//判断key是否存在以及值的函数 if v := ctx.value(k); v != nil { fmt.println("found value:", v) return } fmt.println("key not found:", k) } k := favcontextkey("language") ctx := context.withvalue(context.background(), k, "go") //使用自定义类型作为key f(ctx, k) //found value: go f(ctx, favcontextkey("color")) //key not found: color ctx2 := context.withvalue(ctx, "language", "java") //使用string,试图覆盖之前的key对应的值 f(ctx2, k) //found value: go ,并没有被覆盖 f(ctx2, "language") //found value: java ,两个key互相独立 }
而在使用context来存储key-value的时候,最好的方式是不导出key,key只在包内可访问,在包内定义,然后包提供安全的访问方法来保存key-value和取key-value。如:
type user struct {// user是我们要作为value保存在contex里的值 //自定义字段 } type key int //key是我们定义在包内的key类型,这样不会与其他包的冲突 var userkey key//key类型的变量,用作context里的key。 // newcontext方法用来将value存入context func newcontext(ctx context.context, u *user) context.context { return context.withvalue(ctx, userkey, u) } // fromcontext用来取value func fromcontext(ctx context.context) (*user, bool) { u, ok := ctx.value(userkey).(*user) return u, ok }
看一下withvalue的实现是咋样的:
func withvalue(parent context, key, val interface{}) context { if key == nil {//没有key肯定是不行的辣 panic("nil key") } if !reflectlite.typeof(key).comparable() {//key不可比较也是不行的辣,comparable()是接口type的一个方法,不可比较,那么取value的时候,咋知道你到底想取啥 panic("key is not comparable") } return &valuectx{parent, key, val} }
看到返回了一个valuectx对象,这是个啥,康康:
type valuectx struct { context key, val interface{} }
好家伙,原来是包装了一个context,加俩字段key和value。这还了得,那如果多withvalue几次,那不得串成长长的一个链。可以看到这里每withvalue一次,就多一个节点,这个链可够长,取value就是向上遍历这个context链了嘛。来康康取值方法value()的实现,其实我们知道value(key interface{}) interface{}是context接口的一个方法,所以我们看下这个在valuectx结构中的实现:
func (c *valuectx) value(key interface{}) interface{} { if c.key == key {//key的可比性就是用在这里的 return c.val } return c.context.value(key)//如果当前valuectx里没有找到这个key,就向上遍历链,直到找到为止 }
这个向上遍历的链,如果一直找不到key呢,就会终止在顶层context:background或者todo
看一哈:
var ( background = new(emptyctx) todo = new(emptyctx) ) func background() context { return background } func todo() context { return todo }
是滴,context.background()和context.todo()就造了这么个玩意儿,emptyctx类型的一个对象,emptyctx是什么东西呢,来截取一小部分康康:
type emptyctx int func (*emptyctx) deadline() (deadline time.time, ok bool) { return } func (*emptyctx) done() <-chan struct{} { return nil } func (*emptyctx) err() error { return nil } func (*emptyctx) value(key interface{}) interface{} { return nil }
好家伙是个惊天骗局,本质上只是个int,居然还实现了context接口。
其value返回nil,破案了。
func background() context
返回一个非nil非空的context,永远不会被取消,也没有value,没有deadline。一般用于main函数里,或者初始化,用作顶层的context。
func todo() context
返回一个非nil非空的context。当不知道用什么context,或者还不使用context但是有这个入参的时候,可以用这个。
如对本文有疑问, 点击进行留言回复!!
VSCode1.4 搭建Golang的开发调试环境(遇到很多问题)
网友评论