在Go语言中实现高并发请求可以通过goroutine和channel来实现异步操作。下面是一个简单的示例代码:
package mainimport ("fmt""net/http""time")func main() {start := time.Now()urls := []string{"https://www.google.com","https://www.facebook.com","https://www.youtube.com",}// 创建一个无缓冲的channelch := make(chan string)for _, url := range urls {go fetch(url, ch)}for range urls {fmt.Println(<-ch)}fmt.Printf("总共耗时: %.2fs\n", time.Since(start).Seconds())}func fetch(url string, ch chan string) {start := time.Now()resp, err := http.Get(url)if err != nil {ch <- fmt.Sprint(err)return}resp.Body.Close()elapsed := time.Since(start).Seconds()ch <- fmt.Sprintf("请求 %s 耗时 %.2fs", url, elapsed)}在这个示例中,我们定义了一个包含三个URL的切片,然后使用goroutine并发地请求这些URL。每个goroutine都会调用fetch函数来发送HTTP请求并计算耗时,然后将结果发送到一个无缓冲的channel中。最后我们通过从channel中读取结果来打印每个请求的耗时,并计算总共的耗时。
通过使用goroutine和channel,我们可以实现高并发地发送HTTP请求并处理响应,从而提高程序的性能和效率。


