go - 多线程 HTTP 客户端请求的重构程序
问题描述
我正在阅读 Google Places 包装器的文档,但它仅支持 Google Nearby Search。这真的不是一个巨大的瓶颈。
我的脚本执行附近搜索以查找该区域的 Place_ID,然后继续执行 Places Details 查询以从该特定 Google Maps 业务条目中获取所有数据。
这个 Places Details 查询是瓶颈所在,我希望能得到关于我编写的这个脚本的一些反馈。
看起来它不是多线程的,但是当我将“线程数”从 1 增加到 40 时,我的示例脚本运行时间从 40 秒下降到 12 秒。
我不得不做很多复制和粘贴,反复试验,才能让这个功能发挥作用。我非常感谢这里的帮助。
- 为什么当我将线程数增加到 40 时它运行得更快?
- 如何使用多线程加快速度?
package main
import (
"sync"
"bufio"
"os"
"fmt"
"net/http"
"time"
"io/ioutil"
"strings"
"log"
"crypto/tls"
"googlemaps.github.io/maps"
"bytes"
"encoding/json"
)
var threadCount = 40
var wg sync.WaitGroup
var api_key = "api_key"
var top_cities_gps = "./top_cities_gps"
var next_page_token = ""
var business_types = []string{"accounting", "art_gallery"}
var connector = &http.Transport{
MaxIdleConns: threadCount,
ring('\n')
if err != nil {
log.Fatalf("read file line error: %v", err)
return
}
_ = line
// alright! let's kick this up a notch, and start scraping!!! :D
// looping all business types
for i, s := range business_types {
// now let's hit Google Places API for a NearbySearch!
//
searchPlaces("", s, strings.TrimSpace(line))
}
}
}
func main() {
GoGoogle()
}
解决方案
threadCount
名称错误。它仅用于设置MaxIdleConns
in HTTP 传输。根据文档:
// MaxIdleConns controls the maximum number of idle (keep-alive)
// connections across all hosts. Zero means no limit.
因此,当您threadCount
从 1 增加到 40 时,您增加了保持活动连接的限制。从这种用法看来,设置threadCount
为 0 会给你最好的结果。
threadCount
我建议你彻底摆脱。
推荐阅读
- c# - 如何将多个 JSON 列表项传递给 HttpPost?
- python - 可行的?带有 selenium 的表单自动化 webapp - [服务器端]
- python - 没有库的python中的自定义crc32计算
- java - Retrofit + Gson 无法解析简单的 Map
- css - Angular 应用程序中所有页面的字体系列更改
- python - 为什么以下 Python 代码不删除列?
- xamarin.forms - Xamarin.Forms 仅在一个平台 (iOS) 上更改条目的占位符颜色和文本颜色
- azure - 在 ARM 模板中获取 Azure 存储 dacpac 文件
- python - 如何在 Python 3.7 中运行 manim 示例?
- php - 如果数组的元素与