我正在为客户开发基于网络的 RESTful API。除了一个请求外,一切都很好,我需要为每一行请求 Foursquare API。
此请求的 URL 是:http://api.example.com/v1/users/times .
当前对该 url 请求的响应是:
{
"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"
}
但是,response.user.times
数组中返回的 venue_fq_id
与 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'];
}
最佳答案
您正在浪费大量时间来实例化/拆除 CURL 对象。这会阻止您利用 HTTP keep-alives,强制 curl 为您发出的每个请求启动一个新的 TCP 连接。
curl 句柄可以 重复使用。例如
$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);
}
关于php - 优化性能 : Many CURL requests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11924762/