利用通道实现并发的POST API调用并将结果记录在文件中
来源:stackoverflow
时间:2024-03-14 21:03:29 377浏览 收藏
golang学习网今天将给大家带来《利用通道实现并发的POST API调用并将结果记录在文件中》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
我正在尝试用 go 设计一个 http 客户端,它能够对 web 服务进行并发 api 调用,并在文本文件中写入一些数据。
func gettotalcalls() int { reader := bufio.newreader(os.stdin) ... return callint }
gettotalcolls
决定我要拨打多少个电话,输入来自终端。
func writetofile(s string, nameprefix string) { filestore := fmt.sprintf("./data/%s_calls.log", nameprefix) ... defer f.close() if _, err := f.writestring(s); err != nil { log.println(err) } }
writetofile
将从缓冲通道同步将数据写入文件。
func makerequest(url string, ch chan<- string, id int) { var jsonstr = []byte(`{"from": "saru", "message": "saru to discovery. over!"}`) req, err := http.newrequest("post", url, bytes.newbuffer(jsonstr)) req.header.set("content-type", "application/json") client := &http.client{} start := time.now() resp, err := client.do(req) if err != nil { panic(err) } secs := time.since(start).seconds() defer resp.body.close() body, _ := ioutil.readall(resp.body) ch <- fmt.sprintf("%d, %.2f, %d, %s, %s\n", id, secs, len(body), url, body) }
这是在 go routine 中进行 api 调用的函数。
最后这是 main 函数,它将数据从 go 例程发送到 bufferend 通道,稍后我遍历字符串的 bufferend 通道并将数据写入文件。
func main() { urlPrefix := os.Getenv("STARCOMM_GO") url := urlPrefix + "discovery" totalCalls := getTotalCalls() queue := make(chan string, totalCalls) for i := 1; i <= totalCalls; i++ { go makeRequest(url, queue, i) } for item := range queue { fmt.Println(item) writeToFile(item, fmt.Sprint(totalCalls)) } }
问题是在调用结束时,缓冲以某种方式阻塞,并且程序永远等待所有调用的结束。有人有更好的方法来设计这样的用例吗?我的最终目标是检查不同数量的并发发布请求,每个调用需要多少时间,以便对 5、10、50、100、500、1000 组并发调用的 api 端点进行基准标记。
解决方案
必须有东西 close(queue)
。否则 range 队列
将阻塞。如果你想 range 队列
,你必须确保在最终客户端完成后关闭此通道。
但是...甚至不清楚您是否需要 range 队列
,因为您确切知道将获得多少结果 - 它是 totalcalls
。您只需要循环多次从 queue
接收即可。
我相信您的用例与 Worker Pools example on gobyexample 类似,因此您可能需要检查一下。以下是该示例的代码:
// In this example we'll look at how to implement // a _worker pool_ using goroutines and channels. package main import ( "fmt" "time" ) // Here's the worker, of which we'll run several // concurrent instances. These workers will receive // work on the `jobs` channel and send the corresponding // results on `results`. We'll sleep a second per job to // simulate an expensive task. func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("worker", id, "started job", j) time.Sleep(time.Second) fmt.Println("worker", id, "finished job", j) results <- j * 2 } } func main() { // In order to use our pool of workers we need to send // them work and collect their results. We make 2 // channels for this. const numJobs = 5 jobs := make(chan int, numJobs) results := make(chan int, numJobs) // This starts up 3 workers, initially blocked // because there are no jobs yet. for w := 1; w <= 3; w++ { go worker(w, jobs, results) } // Here we send 5 `jobs` and then `close` that // channel to indicate that's all the work we have. for j := 1; j <= numJobs; j++ { jobs <- j } close(jobs) // Finally we collect all the results of the work. // This also ensures that the worker goroutines have // finished. An alternative way to wait for multiple // goroutines is to use a [WaitGroup](waitgroups). for a := 1; a <= numJobs; a++ { <-results } }
你的“worker”发出 http 请求,否则它的模式几乎相同。请注意最后的 for
循环,它从通道读取已知次数。
到这里,我们也就讲完了《利用通道实现并发的POST API调用并将结果记录在文件中》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习