go之多线程 HTTP 客户端请求的重构程序

jillzhang 阅读:71 2025-06-02 22:19:02 评论:0

关闭。这个问题需要更多 focused .它目前不接受答案。












想改进这个问题?更新问题,使其仅关注一个问题 editing this post .

2年前关闭。




Improve this question




我正在阅读 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在 HTTP 传输中。根据文档:

     // MaxIdleConns controls the maximum number of idle (keep-alive) 
     // connections across all hosts. Zero means no limit. 
    

    所以当你增加 threadCount从 1 到 40,您增加了保持事件连接的限制。从这个用法看来,设置 threadCount到 0 会给你最好的结果。

    我建议你摆脱 threadCount完全地。


    标签:多线程
    声明

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    关注我们

    一个IT知识分享的公众号