context 实际上并不是一个罕见的设计,在许多语言的基础库里面都有出现,有所不同的是,大部分 sdk,尤其是过程语言,使用context 一般是用来
传递数据
,golang 的 context设计同时还带有传递控制能力
的作用,实现方式为使用 cancel/timeout.
来自官方文档: https://blog.golang.org/context: Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue. When a Context is canceled, all Contexts derived from it are also canceled.
上层请求创建 context,附带信息或者控制能力,传递给下一层,当上一层出现错误,或者取消的时候,下次收到信号,也取消处理,避免浪费。
main goroutine --context1--> goroutine1 --context2--> goroutine2
Context 是 context 包对外暴露的接口,该接口定义了四个方法,其中包括:
// A Context carries a deadline, cancelation signal, and request-scoped values
// across API boundaries. Its methods are safe for simultaneous use by multiple
// goroutines.
type Context interface {
// Done returns a channel that is closed when this Context is canceled
// or times out.
Done() <-chan struct{}
// Err indicates why this context was canceled, after the Done channel
// is closed.
Err() error
// Deadline returns the time when this Context will be canceled, if any.
Deadline() (deadline time.Time, ok bool)
// Value returns the value associated with key or nil if none.
Value(key interface{}) interface{}
}
官方例子
// 一个关联知识点
// 1. 对 nil channel中读写数据会一直被block。
// 2. close的channel 读立即返回零值,写会panic,无论读写都不会阻塞。
// 常用的使用模式 break if cancel
func Stream(ctx context.Context, out chan<- Value) error {
for {
v, err := DoSomething(ctx)
if err != nil { return err }
select {
case <-ctx.Done():
return ctx.Err()
case out <- v:
}
}
}
// 简化的 google search 例子
func handleSearch(w http.ResponseWriter, req *http.Request) {
timeout, err := time.ParseDuration(req.FormValue("timeout"))
if err == nil {
ctx, cancel = context.WithTimeout(context.Background(), timeout)
} else {
ctx, cancel = context.WithCancel(context.Background())
}
defer cancel() // Cancel ctx as soon as handleSearch returns.
results, err := search(ctx, query)
// ...略
}
// Search sends query to Google search and returns the results.
func Search(ctx context.Context, query string) (Results, error) {
// ...略
err = httpDo(ctx, req, func(resp *http.Response, err error) error {
// 略
results = xxx
return nil
})
// httpDo waits for the closure we provided to return, so it's safe to read results here.
return results, err
}
// httpDo issues the HTTP request and calls f with the response. If ctx.Done is
// closed while the request or f is running, httpDo cancels the request, waits
// for f to exit, and returns ctx.Err. Otherwise, httpDo returns f's error.
func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
// Run the HTTP request in a goroutine and pass the response to f.
c := make(chan error, 1)
req = req.WithContext(ctx)
go func() { c <- f(http.DefaultClient.Do(req)) }()
select {
case <-ctx.Done():// 被取消了 (可能是 timeout 触发的)
<-c // Wait for f to return.
return ctx.Err()
case err := <-c:
return err
}
}
来自 rancher/wranger
// 另一个例子 这是一个收到一个信息 stop 两个信号退出的函数
func SetupSignalHandler(parent context.Context) context.Context {
close(onlyOneSignalHandler) // panics when called twice
ctx, cancel := context.WithCancel(parent)
c := make(chan os.Signal, 2)
signal.Notify(c, shutdownSignals...)
go func() {
<-c
cancel() // 收到信号,取消 ctx, 后面使用这个 ctx 的任务都会 done
<-c
os.Exit(1) // second signal. Exit directly.
}()
return ctx
}
来自 kubernetes scheduler
// 另一个例子 来自kubernetes scheduler
func Run(c schedulerserverconfig.CompletedConfig, stopCh <-chan struct{}) error {
// ...略
// Prepare a reusable run function.
run := func(ctx context.Context) {
sched.Run()
<-ctx.Done()
}
ctx, cancel := context.WithCancel(context.TODO()) // TODO once Run() accepts a context, it should be used here
defer cancel()
go func() {
select {
case <-stopCh:
cancel()
case <-ctx.Done():
}
}()
// If leader election is enabled, run via LeaderElector until done and exit.
if c.LeaderElection != nil {
// ...略
leaderElector.Run(ctx)
return fmt.Errorf("lost lease")
}
// Leader election is disabled, so run inline until done.
run(ctx)
return fmt.Errorf("finished without leader elect")
}
实战:再来最后一个例子,如何实现这样一个函数, retry f,直到 f 成功或者 timeout
对于这个例子 更通用的实现见 k8s.io/apimachinery/pkg/util/wait/wait.go
不过 wait 中的 timeout 并不准确, 它在 重复的时候才会检查 timeout
func Retry(fn func(ctx context.Context) error, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
c := make(chan error, 1)
for {
go func() { c <- fn(ctx) }()
select {
case <-ctx.Done():
return ctx.Err() // timeout error
case err := <-c:
if err == nil {
return nil
}
}
}
}
参考:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。