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

2020-01-28 13:17:47丽君

你可以通过运行服务器并在浏览器上打开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)
}