3

我正在为客户端开发基于 Web 的 RESTful api。除了一个请求之外,一切都很好,我需要为每一行请求 Foursquare API。

此请求的 URL 是:http://api.example.com/v1/users/times

目前对该网址的请求的响应是:

{
"response": {
    "user": {
        ... some user info ...
        "times": [
            {
                "id": "8",
                "venue_fq_id": "4b81eb25f964a52000c430e3",
                "user_id": "1",
                "wait_length": "4468",
                "created_at": "2012-06-09 21:45:43"
            },
            {
                "id": "9",
                "venue_fq_id": "4aad285af964a520c05e20e3",
                "user_id": "1",
                "wait_length": "8512",
                "created_at": "2012-06-09 21:45:43"
            },
            {
                "id": "10",
                "venue_fq_id": "42377700f964a52024201fe3",
                "user_id": "1",
                "wait_length": "29155",
                "created_at": "2012-06-09 21:45:44"
            },
            {
                "id": "11",
                "venue_fq_id": "45c88764f964a5206e421fe3",
                "user_id": "1",
                "wait_length": "33841",
                "created_at": "2012-06-09 21:45:44"
            },
            {
                "id": "12",
                "venue_fq_id": "430d0a00f964a5203e271fe3",
                "user_id": "1",
                "wait_length": "81739",
                "created_at": "2012-06-09 21:45:44"
            }
        ]
    }
},
"stat": "ok"
}

但是,数组venue_fq_id中返回的response.user.times值是相对于 Foursquare API 上的一个场所。我尝试为每一行向 Foursquare API 运行 curl 请求,但性能非常慢。请您提供一些示例,说明我可以通过哪些方式来加快性能,同时检索我每次访问请求 F/Q API 时会获取的相同信息?

这是我的代码:

$query = $this->db->query("SELECT * FROM `wait_times` WHERE `user_id` = ?", array($email_address));

$wait_times = $query->result();

foreach ($wait_times as $wait_time) {

    $wait_time->venue = $this->venue_info($wait_time->venue_fq_id);

}

function venue_info($fq_id) {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.foursquare.com/v2/venues/4b522afaf964a5200b6d27e3");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $response = json_decode(curl_exec($ch));
    curl_close($ch);

    return $response['response']['venue'];

}
4

2 回答 2

9

您正在浪费大量时间实例化/拆除 CURL 对象。这可以防止您利用 HTTP keep-alives,强制 curl 为您发出的每个请求启动一个新的 tcp 连接。

卷曲手柄可以重复使用。例如

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


function venue_info($fq_id) {
   global $ch;
   curl_setopt($ch, CURLOPT_URL, "https://api.foursquare.com/v2/venues/4b522afaf964a5200b6d27e3");
   $resp = curl_exec($ch) or die(curl_error($ch));
   $json = json_decode($resp);
   return($json);
}
于 2012-08-12T18:43:18.557 回答
0

Foursquare API 提供的multi端点允许您将最多五个查询组合成一个请求。

于 2012-08-12T18:48:55.047 回答