go - 进行批量调用时http请求中的Golang上下文
问题描述
我正在寻找了解使用带有上下文超时的 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)
}
解决方案
来自上下文文档
WithCancel、WithDeadline 和 WithTimeout 函数采用 Context(父)并返回派生的 Context(子)和 CancelFunc。调用 CancelFunc 会取消子项及其子项,删除父项对子项的引用,并停止任何关联的计时器
因此上下文由孩子及其孩子共享。所有请求将在 200 毫秒后超时。
推荐阅读
- xml - XML 到 Powershell 哈希表
- routing - 链接器、kubernetes 和 dtab
- go - 将值附加到切片时,值与原始值不同
- angular - 是否可以在角度组件模板中使用 let 为变量赋值?
- php - 为什么这不会输出一些结果?
- c - C如何转义printf中的特定字符?
- javascript - RxJs:当 Observable 以 .fromEvent 开头时,抛出错误不允许 .retryWhen
- scala - How to use placeholder syntax properly with map?
- go - goroutine 的意外输出
- aws-lambda - AWS::Serverless::Function 和 AWS::Lambda::Function 之间的区别