context 作用
- context 主要用来在 goroutine 之间传递上下文信息,包括:取消信号、超时时间、截止时间、k-v 等
Context 使用原则
- 不要将 Context 放入结构体,Context应该作为第一个参数传
入,命名为ctx。 - 即使函数允许,也不要传入nil的 Context。如果不知道用哪种
Context,可以使用context.TODO()。 - 使用context的Value相关方法,只应该用于在程序和接口中传递
和请求相关数据,不能用它来传递一些可选的参数 - 相同的 Context 可以传递给在不同的goroutine;Context 是
并发安全的。
定义的接口
- Context 是一个接口,定义了 4 个方法,它们都是幂等的。也就是说连续多次调用同一个方法,得到的结果都是相同的。
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled.
Done() <-chan struct{}
// Err returns a non-nil error value after Done is closed.
Err() error
// Value returns the value associated with this context for key.
Value(key interface{}) interface{}
}
简单介绍一下其中的方法
- Done会返回一个channel,当该context被取消的时候,该channel会被关闭,同时对应的使用该context的routine也应该结束并返回。
- Context中的方法是协程安全的,这也就代表了在父routine中创建的context,可以传递给任意数量的routine并让他们同时访问。
- Deadline会返回一个超时时间,routine获得了超时时间后,可以对某些io操作设定超时时间。
- Value可以让routine共享一些数据,当然获得数据是协程安全的。
参考链接:Golang官方博客