同时运行循环中的Go语言超时
来源:stackoverflow
2024-03-05 17:00:28
0浏览
收藏
“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《同时运行循环中的Go语言超时》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
问题内容
我需要在 parallel 中运行请求,而不是一个接一个地运行请求,但会超时。现在我可以用 go 来做吗?
这是我需要并行运行的具体代码,这里的技巧也是使用超时,即根据超时等待所有请求,并在完成后获取响应。
for _, test := range testers {
checker := newtap(test.name, test.url, test.timeout)
res, err := checker.check()
if err != nil {
fmt.println(err)
}
fmt.println(res.name)
fmt.println(res.res.statuscode)
}
这是所有代码(工作代码) https://play.golang.org/p/cxnjj6pw_cf
package main
import (
`fmt`
`net/http`
`time`
)
type HT interface {
Name() string
Check() (*testerResponse, error)
}
type testerResponse struct {
name string
res http.Response
}
type Tap struct {
url string
name string
timeout time.Duration
client *http.Client
}
func NewTap(name, url string, timeout time.Duration) *Tap {
return &Tap{
url: url,
name: name,
client: &http.Client{Timeout: timeout},
}
}
func (p *Tap) Check() (*testerResponse, error) {
response := &testerResponse{}
req, err := http.NewRequest("GET", p.url, nil)
if err != nil {
return nil, err
}
res, e := p.client.Do(req)
response.name = p.name
response.res = *res
if err != nil {
return response, e
}
return response, e
}
func (p *Tap) Name() string {
return p.name
}
func main() {
var checkers []HT
testers := []Tap{
{
name: "first call",
url: "http://stackoverflow.com",
timeout: time.Second * 20,
},
{
name: "second call",
url: "http://www.example.com",
timeout: time.Second * 10,
},
}
for _, test := range testers {
checker := NewTap(test.name, test.url, test.timeout)
res, err := checker.Check()
if err != nil {
fmt.Println(err)
}
fmt.Println(res.name)
fmt.Println(res.res.StatusCode)
checkers = append(checkers, checker)
}
}解决方案
go 中流行的并发模式是使用工作池。
基本工作池使用两个通道;一个用于放置作业,另一个用于读取结果。在这种情况下,我们的作业通道将是 tap 类型,我们的结果通道将是 testerresponse 类型。
工人
从作业通道获取作业并将结果放入结果通道。
// worker defines our worker func. as long as there is a job in the
// "queue" we continue to pick up the "next" job
func worker(jobs <-chan tap, results chan<- testerresponse) {
for n := range jobs {
results <- n.check()
}
}
工作
要添加作业,我们需要迭代 testers 并将它们放入我们的作业频道。
// makejobs fills up our jobs channel
func makejobs(jobs chan<- tap, taps []tap) {
for _, t := range taps {
jobs <- t
}
}
结果
为了读取结果,我们需要迭代它们。
// getresults takes a job from our worker pool and gets the result
func getresults(tr <-chan testerresponse, taps []tap) {
for range taps {
r := <- tr
status := fmt.sprintf("'%s' to '%s' was fetched with status '%d'\n", r.name, r.url, r.res.statuscode)
if r.err != nil {
status = fmt.sprintf(r.err.error())
}
fmt.println(status)
}
}
最后,我们的主要功能。
func main() {
// make buffered channels
buffer := len(testers)
jobspipe := make(chan tap, buffer) // jobs will be of type `tap`
resultspipe := make(chan testerresponse, buffer) // results will be of type `testerresponse`
// create worker pool
// max workers default is 5
// maxworkers := 5
// for i := 0; i < maxworkers; i++ {
// go worker(jobspipe, resultspipe)
// }
// the loop above is the same as doing:
go worker(jobspipe, resultspipe)
go worker(jobspipe, resultspipe)
go worker(jobspipe, resultspipe)
go worker(jobspipe, resultspipe)
go worker(jobspipe, resultspipe)
// ^^ this creates 5 workers..
makejobs(jobspipe, testers)
getresults(resultspipe, testers)
}
把它们放在一起
我将“第二次调用”的超时更改为一毫秒,以显示超时的工作原理。
package main
import (
"fmt"
"net/http"
"time"
)
type ht interface {
name() string
check() (*testerresponse, error)
}
type testerresponse struct {
err error
name string
res http.response
url string
}
type tap struct {
url string
name string
timeout time.duration
client *http.client
}
func newtap(name, url string, timeout time.duration) *tap {
return &tap{
url: url,
name: name,
client: &http.client{timeout: timeout},
}
}
func (p *tap) check() testerresponse {
fmt.printf("fetching %s %s \n", p.name, p.url)
// theres really no need for newtap
nt := newtap(p.name, p.url, p.timeout)
res, err := nt.client.get(p.url)
if err != nil {
return testerresponse{err: err}
}
// need to close body
res.body.close()
return testerresponse{name: p.name, res: *res, url: p.url}
}
func (p *tap) name() string {
return p.name
}
// makejobs fills up our jobs channel
func makejobs(jobs chan<- tap, taps []tap) {
for _, t := range taps {
jobs <- t
}
}
// getresults takes a job from our jobs channel, gets the result, and
// places it on the results channel
func getresults(tr <-chan testerresponse, taps []tap) {
for range taps {
r := <-tr
status := fmt.sprintf("'%s' to '%s' was fetched with status '%d'\n", r.name, r.url, r.res.statuscode)
if r.err != nil {
status = fmt.sprintf(r.err.error())
}
fmt.printf(status)
}
}
// worker defines our worker func. as long as there is a job in the
// "queue" we continue to pick up the "next" job
func worker(jobs <-chan tap, results chan<- testerresponse) {
for n := range jobs {
results <- n.check()
}
}
var (
testers = []tap{
{
name: "1",
url: "http://google.com",
timeout: time.second * 20,
},
{
name: "2",
url: "http://www.yahoo.com",
timeout: time.second * 10,
},
{
name: "3",
url: "http://stackoverflow.com",
timeout: time.second * 20,
},
{
name: "4",
url: "http://www.example.com",
timeout: time.second * 10,
},
{
name: "5",
url: "http://stackoverflow.com",
timeout: time.second * 20,
},
{
name: "6",
url: "http://www.example.com",
timeout: time.second * 10,
},
{
name: "7",
url: "http://stackoverflow.com",
timeout: time.second * 20,
},
{
name: "8",
url: "http://www.example.com",
timeout: time.second * 10,
},
{
name: "9",
url: "http://stackoverflow.com",
timeout: time.second * 20,
},
{
name: "10",
url: "http://www.example.com",
timeout: time.second * 10,
},
{
name: "11",
url: "http://stackoverflow.com",
timeout: time.second * 20,
},
{
name: "12",
url: "http://www.example.com",
timeout: time.second * 10,
},
{
name: "13",
url: "http://stackoverflow.com",
timeout: time.second * 20,
},
{
name: "14",
url: "http://www.example.com",
timeout: time.second * 10,
},
}
)
func main() {
// make buffered channels
buffer := len(testers)
jobspipe := make(chan tap, buffer) // jobs will be of type `tap`
resultspipe := make(chan testerresponse, buffer) // results will be of type `testerresponse`
// create worker pool
// max workers default is 5
// maxworkers := 5
// for i := 0; i < maxworkers; i++ {
// go worker(jobspipe, resultspipe)
// }
// the loop above is the same as doing:
go worker(jobspipe, resultspipe)
go worker(jobspipe, resultspipe)
go worker(jobspipe, resultspipe)
go worker(jobspipe, resultspipe)
go worker(jobspipe, resultspipe)
// ^^ this creates 5 workers..
makejobs(jobspipe, testers)
getresults(resultspipe, testers)
}
哪些输出:
// fetching http://stackoverflow.com // fetching http://www.example.com // get "http://www.example.com": context deadline exceeded (client.timeout exceeded while awaiting headers) // 'first call' to 'http://stackoverflow.com' was fetched with status '200'
在 golang 中可以通过不同的方式实现并行性。 这是一种幼稚的方法,具有等待组、互斥体和无限的 go 例程,不推荐。 我认为使用通道是实现并行性的首选方式。
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
type HT interface {
Name() string
Check() (*testerResponse, error)
}
type testerResponse struct {
name string
res http.Response
}
type Tap struct {
url string
name string
timeout time.Duration
client *http.Client
}
func NewTap(name, url string, timeout time.Duration) *Tap {
return &Tap{
url: url,
name: name,
client: &http.Client{
Timeout: timeout,
},
}
}
func (p *Tap) Check() (*testerResponse, error) {
response := &testerResponse{}
req, err := http.NewRequest("GET", p.url, nil)
if err != nil {
return nil, err
}
res, e := p.client.Do(req)
if e != nil {
return response, e
}
response.name = p.name
response.res = *res
return response, e
}
func (p *Tap) Name() string {
return p.name
}
func main() {
var checkers []HT
wg := sync.WaitGroup{}
locker := sync.Mutex{}
testers := []Tap{
{
name: "first call",
url: "http://google.com",
timeout: time.Second * 20,
},
{
name: "second call",
url: "http://www.example.com",
timeout: time.Millisecond * 100,
},
}
for _, test := range testers {
wg.Add(1)
go func(tst Tap) {
defer wg.Done()
checker := NewTap(tst.name, tst.url, tst.timeout)
res, err := checker.Check()
if err != nil {
fmt.Println(err)
}
fmt.Println(res.name)
fmt.Println(res.res.StatusCode)
locker.Lock()
defer locker.Unlock()
checkers = append(checkers, checker)
}(test)
}
wg.Wait()
}理论要掌握,实操不能落!以上关于《同时运行循环中的Go语言超时》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
在Golang中如何截断删除大文件的前N个字节?
- 上一篇
- 在Golang中如何截断删除大文件的前N个字节?
- 下一篇
- 掌握PHPDoc:让代码自我解释
查看更多
最新文章
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 478浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3181次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3392次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3423次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4527次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3801次使用
查看更多
相关文章
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览

