当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go语言中的上下文取消操作详解

Go语言中的上下文取消操作详解

2018年08月06日  | 移动技术网IT编程  | 我要评论

前言

许多使用go的人,都会用到它的上下文库。大多数使用 context 进行下游操作,比如发出http调用,或者从数据库获取数据,或者在协程中执行异步操作。最常见的用法是传递可由所有下游操作使用的公共数据。然而,一个不太为人所知,但非常有用的上下文特性是,它能够在中途取消或停止一个操作。

本篇文章将解释我们如何利用上下文库的取消特性,并通过一些模式和最佳实践来使用取消,使你的程序更快、更健壮。

为什么需要取消?

简而言之,我们需要取消,以防止我们的系统做不不需要的工作。

考虑http服务器对数据库的调用的常见情况,并将查询的数据返回给客户端:


时间图,如果一切都很完美,就会是这样的:

但是,如果客户端取消了中间的请求,会发生什么呢?例如,如果客户端关闭了他们的浏览器,这可能会发生。如果没有取消,应用服务器和数据库将继续执行它们的工作,即使工作的结果将被浪费:

理想情况下,如果我们知道进程(在本例中是http请求)停止了,我们希望流程的所有下游组件停止工作:

1、上下文取消

现在我们知道了为什么需要取消,让我们来看看如何实现它。因为“取消”的事件与交易或正在执行的操作高度相关,所以它与上下文捆绑在一起是很自然的。

取消的有两个方面,你可能想要实现:

  • 监听取消事件
  • 提交取消事件

2、监听取消事件

上下文类型提供了 done() 方法,每当上下文收到取消事件时,它都会返回接收空 struct{} 类型的通道。监听取消事件就像等待 <-ctx.done() 一样简单。

例如,让我们考虑一个http服务器,它需要两秒钟来处理一个事件。如果在此之前请求被取消,我们希望立即返回:

func main() {
  // create an http server that listens on port 8000
 http.listenandserve(":8000", http.handlerfunc(func(w http.responsewriter, r *http.request) {
 ctx := r.context()
 // this prints to stdout to show that processing has started
 fmt.fprint(os.stdout, "processing request\n")
 // we use `select` to execute a peice of code depending on which
 // channel receives a message first
 select {
   case <-time.after(2 * time.second):
 // if we receive a message after 2 seconds
 // that means the request has been processed
 // we then write this as the response
 w.write([]byte("request processed"))
   case <-ctx.done():
 // if the request gets cancelled, log it
 // to stderr
 fmt.fprint(os.stderr, "request cancelled\n")
 }
 }))
}

你可以通过运行服务器并在浏览器上打开localhost:8000来测试。如果你在2秒前关闭浏览器,你应该会看到在终端窗口上打印的“请求取消”。

3、提交取消事件

如果你有一个可以被取消的操作,你将不得不通过上下文发出取消事件。这可以通过 context 包中的 withcancel 函数来完成,它返回一个上下文对象和一个函数。这个函数没有参数,也不返回任何东西,当你想要取消上下文时调用。

考虑两个从属操作的情况。在这里,“依赖”意味着如果一个失败了,另一个就没有意义了。在这种情况下,如果我们在早期就知道其中一个操作失败了,我们想要取消所有的依赖操作。

func operation1(ctx context.context) error {
 // let's assume that this operation failed for some reason
 // we use time.sleep to simulate a resource intensive operation
 time.sleep(100 * time.millisecond)
 return errors.new("failed")
}

func operation2(ctx context.context) {
 // we use a similar pattern to the http server
 // that we saw in the earlier example
 select {
  case <-time.after(500 * time.millisecond):
 fmt.println("done")
  case <-ctx.done():
 fmt.println("halted operation2")
 }
}

func main() {
 // create a new context
 ctx := context.background()

 // create a new context, with its cancellation function
 // from the original context
 ctx, cancel := context.withcancel(ctx)

 // run two operations: one in a different go routine
 go func() {
 err := operation1(ctx)
 // if this operation returns an error
 // cancel all operations using this context
 if err != nil {
 cancel()
 }
 }()
 // run operation2 with the same context we use for operation1
 operation2(ctx)
}

4、基于时间取消

任何需要在请求的最大持续时间内维护sla(服务水平协议)的应用程序都应该使用基于时间的取消。该api几乎与前面的示例相同,并添加了一些内容:

// the context will be cancelled after 3 seconds
// if it needs to be cancelled earlier, the `cancel` function can
// be used, like before

ctx, cancel := context.withtimeout(ctx, 3*time.second)

// the context will be cancelled on 2009-11-10 23:00:00
ctx, cancel := context.withdeadline(ctx, time.date(2009, time.november, 10, 23, 0, 0, 0, time.utc))

例如,考虑对外部服务进行http api调用。如果服务花费的时间太长,最好是尽早失败并取消请求:

func main() {
 // create a new context
 // with a deadline of 100 milliseconds
 ctx := context.background()
 ctx, _ = context.withtimeout(ctx, 100*time.millisecond)
 // make a request, that will call the google homepage
 req, _ := http.newrequest(http.methodget, "http://google.com", nil)
 // associate the cancellable context we just created to the request
 req = req.withcontext(ctx)

 // create a new http client and execute the request
 client := &http.client{}
 res, err := client.do(req)

 // if the request failed, log to stdout
 if err != nil {
 fmt.println("request failed:", err)
 return
 }

 // print the statuscode if the request succeeds
 fmt.println("response received, status code:", res.statuscode)
}

根据谷歌主页对你的请求的响应速度,你将收到:

response received, status code: 200

或者

request failed: get http://google.com: context deadline exceeded

你可以使用超时来实现上述两个结果。

陷阱和警告

尽管go的上下文取消是一个通用的工具,但是在继续之前,有一些事情是你应该记住的。其中最重要的一点是, 上下文只能被取消一次 。

如果你想在同一个操作中提出多个错误,那么使用上下文取消可能不是最好的选择。使用取消的最惯用的方法是,当你真正想要取消某些东西时,而不仅仅是通知下游进程,错误已经发生了。

你需要记住的另一件事是,相同的上下文实例应该传递给所有你可能想要取消的功能和例程。用 withtimeout 或 withcancel 来包装已经可取消的上下文将会导致多种可能性,你的上下文可以被取消,并且应该避免。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网