【问题标题】:Golang context in http request when making bulk calls进行批量调用时http请求中的Golang上下文
【发布时间】:2021-11-05 08:23:11
【问题描述】:

我正在寻找了解在使用带有上下文超时的 go 标准库进行 http 调用时我应该期望的行为。

我明白如果我这样做:

ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080", nil)

该特定请求将在 200 毫秒内完成。效果很好,我明白了。

我的疑问是,如果我这样做会发生什么:

ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
for loop with a range from 1 to 20 {
  req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080", nil)
}

所以在后一个示例中,我正在使用该上下文执行一堆请求。所有请求会分别超时 200 毫秒,还是会在我开始测距后 200 毫秒后开始失败?

注意:

FATHER_CONTEXT, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)

defer cancel()
for loop with a range from 1 to 20 {
  ctx, cancel := context.WithTimeout(FATHER_CONTEXT, 200*time.Millisecond)
  req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080", nil)
} 

【问题讨论】:

  • 上下文是共享的。当它过期时,它对所有请求都过期。创建上下文 200 毫秒后,所有请求都将失败。
  • 谢谢先生!如果我的新上下文是从以前的上下文中创建的,会发生什么?父上下文也会重置它的超时吗?
  • 我添加了一个例子来说明我的意思
  • 这是文档中的解释。 “子上下文”在父上下文取消时取消。这就是 for 的上下文。

标签: go range timeout


【解决方案1】:

来自Context Documentation

WithCancel、WithDeadline 和 WithTimeout 函数采用 Context (父)并返回一个派生的上下文(子)和一个 取消功能。调用 CancelFunc 会取消子项及其子项, 删除父级对子级的引用,并停止任何关联的 计时器

因此上下文由子及其子共享。所有请求将在 200 毫秒后超时。

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多