如何在返回之前合并两个 gorountines 的结果?

我在 Go 应用程序中有一个 Web 请求处理程序,需要向其他 URL 发出 2 个以上的请求。我想从每个 URL 收集结果,将每个结果合并到一个 JSON 对象中,然后通过我的请求处理程序返回。请求不相互依赖,不需要排序。

在 Go 中执行此操作的最佳模式是什么?我应该使用频道和一个WaitGroup吗?


临摹微笑
浏览 186回答 2
2回答

开满天机

对于简单的事情,我会使用一组局部变量和一些设置这些变量的 goroutine,以及一个等待组来了解一切何时完成:&nbsp; &nbsp; var a string&nbsp; &nbsp; var b string&nbsp; &nbsp; wg := sync.WaitGroup{}&nbsp; &nbsp; wg.Add(2)&nbsp; &nbsp; go func(){&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(5 * time.Second) // make a request&nbsp; &nbsp; &nbsp; &nbsp; a = "foo"&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; }()&nbsp; &nbsp; go func(){&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(3 * time.Second) // make a request&nbsp; &nbsp; &nbsp; &nbsp; b = "bar"&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; }()&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; fmt.Println(a,b) //combine results如果您想要更复杂的行为,如超时或部分结果,那么您可能希望您的子请求在您可以选择的频道上传达结果:// make sure to buffer to max number of senders so garbage collection can clean up// if we time outch := make(chan string, 2)go func() {&nbsp; &nbsp; time.Sleep(5 * time.Second) // make a request&nbsp; &nbsp; ch <- "foo"}()go func() {&nbsp; &nbsp; time.Sleep(2 * time.Second) // make a request&nbsp; &nbsp; ch <- "bar"}()results := []string{}timeout := time.After(4 * time.Second)Loop:for {&nbsp; &nbsp; select {&nbsp; &nbsp; case r := <-ch:&nbsp; &nbsp; &nbsp; &nbsp; results = append(results, r)&nbsp; &nbsp; &nbsp; &nbsp; if len(results) == 2 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break Loop&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; case <-timeout:&nbsp; &nbsp; &nbsp; &nbsp; break Loop&nbsp; &nbsp; }}fmt.Println(results)这并不能完全保留顺序,但如果这很重要,您可以创建另一个频道。无论如何,这就是一般的想法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go