同时运行循环中的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个字节?

- 下一篇
- 掌握PHPDoc:让代码自我解释
查看更多
最新文章
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- 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基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
查看更多
AI推荐
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 28次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 42次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 39次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 51次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 42次使用
查看更多
相关文章
-
- 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浏览