首页 > 解决方案 > 多线程 HTTP 客户端请求的重构程序

问题描述

我正在阅读 Google Places 包装器的文档,但它仅支持 Google Nearby Search。这真的不是一个巨大的瓶颈。

我的脚本执行附近搜索以查找该区域的 Place_ID,然后继续执行 Places Details 查询以从该特定 Google Maps 业务条目中获取所有数据。

这个 Places Details 查询是瓶颈所在,我希望能得到关于我编写的这个脚本的一些反馈。

看起来它不是多线程的,但是当我将“线程数”从 1 增加到 40 时,我的示例脚本运行时间从 40 秒下降到 12 秒。

我不得不做很多复制和粘贴,反复试验,才能让这个功能发挥作用。我非常感谢这里的帮助。

  1. 为什么当我将线程数增加到 40 时它运行得更快?
  2. 如何使用多线程加快速度?
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()
}

标签: gogoogle-places-api

解决方案


threadCount名称错误。它仅用于设置MaxIdleConnsin HTTP 传输。根据文档:

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

因此,当您threadCount从 1 增加到 40 时,您增加了保持活动连接的限制。从这种用法看来,设置threadCount为 0 会给你最好的结果。

threadCount我建议你彻底摆脱。


推荐阅读