我正在使用 PHP 开发一个 Facebook 应用程序,该应用程序获取用户朋友的大量位置信息。随着用户朋友数量的增加,应用程序变得越来越慢。但是我检索的朋友信息越多,结果就越准确。
我曾尝试使用以下方式来加快查询速度:
$facebook->api('/locations?ids=uid1,uid2,uid3,...')
我将它与批处理请求一起使用:
$batched_request = array(
array('method' => 'GET', 'relative_url' => '/locations?ids=uid1,uid2,uid3,...'),
array('method' => 'GET', 'relative_url' => '/locations?ids=uid11,uid12,uid13,...'),
array('method' => 'GET', 'relative_url' => '/locations?ids=uid21,uid22,uid23,...'),
...
);
$batch = $facebook->api('/?batch='.json_encode($batched_request), 'POST');
但仍然需要至少20 秒才能从用户的 100 个随机朋友集中获取位置信息。
实际使用的代码
这部分很好。只需几秒钟即可完成。
$number_of_friends = "100"; // Set the maximum number of friends from which their location information is retrieved
$number_of_friends_per_request = 10; // Set the number of friends per request in the batch
$access_token = $facebook->getAccessToken();
// This is the excerpt of another batched request to get the friend ids
$request = '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+uid,+name+FROM+user+WHERE+uid+IN(SELECT+uid2+FROM+friend+WHERE+uid1+=+me()+order+by+rand()+limit+'.$number_of_friends.')"}]';
$post_url = "https://graph.facebook.com/" . "?batch=" . urlencode($request) . "&access_token=" . $access_token . "&method=post";
$post = file_get_contents($post_url);
$decoded_response = json_decode($post, true);
$friends_json = $decoded_response[0]['body'];
$friends_data = json_decode($friends_json, true);
if (is_array($friends_data)) {
foreach ($friends_data as $friend) {
$selected_friend_ids[] = number_format($friend["uid"], 0, '.', ''); // Since there are exceptionally large id numbers
}
}
但这是有问题的。收到 Facebook 的回复需要很长时间。
// Retrieve the locations of the user's friends using batched request
$i = 0;
$batched_request = array();
while ($i < ($number_of_friends/$number_of_friends_per_request)) {
$i++;
$friend_ids_variable_name = 'friend_ids_part_'.$i;
$$friend_ids_variable_name = array_slice($selected_friend_ids, ($i-1)*$number_of_friends_per_request, $number_of_friends_per_request);
if (!empty($$friend_ids_variable_name)) {
$api_string_ids_variable_name = 'api_string_ids_'.$i;
$$api_string_ids_variable_name = implode(',', $$friend_ids_variable_name);
$batched_request[] = array('method' => 'GET', 'relative_url' => '/locations?ids='.$$api_string_ids_variable_name);
}
}
$batch = $facebook->api('/?batch='.json_encode($batched_request), 'POST');
foreach ($batch as $batch_item) {
$body = $batch_item["body"];
$partial_friends_locations = json_decode($body, true);
foreach ($partial_friends_locations as $friend_id => $friend_locations_data) {
$friend_locations = $friend_locations_data["data"];
foreach ($friend_locations as $friend_location) {
// Process location information...
}
}
}
}
有没有办法使上述请求更快?我放置了一些代码来检查请求的响应时间,它很慢。
- 对于 100 个朋友,平均需要 > 20 秒。
- 对于 200 个朋友,平均需要 > 40 秒。
- 对于 400 位朋友,平均需要 > 80 秒,有时我会收到一条错误消息:“错误代码:1 消息:发生未知错误”
为了让事情变得更快,这意味着:
- 在更短的时间内获得相同数量的信息,或
- 在相同的时间内获取更多信息。