我目前正在编写一个Web应用程序,它通过Twitter API遍历用户时间线。我没有问题获取数据或操纵它。我遇到的问题是速度快。 Twitter API将您可以检索的推文数限制为每页200个。分页是通过在(max_id)中传递一个参数来完成的,这是您在上一页上读到的最后一条推文。反正有没有人能想到提高我收到这些推文的速度?我正在使用abraham oauth lib。我的代码如下:
$twitteroauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth['oauth_token'], $oauth['oauth_token_secret']);
$tweets = $twitteroauth->get('statuses/user_timeline', array ( 'screen_name' => 'user_name', 'count' => 200));
// get first batch of tweets from api
foreach($tweets as $t)
{
$tweets_to_process[] = $t;
}
// get last id of tweet and set prev_id to 0
$last_id = $tweets_to_process[count($tweets_to_process)-1]->id_str;
$prev_id = 0;
$loop_num = 0;
// loop through pages whilst last page returned of api result does not equal last of last result
while($last_id != $prev_id && $loop_num < 4)
{
// get tweets
$tweets = $twitteroauth->get('statuses/user_timeline', array ( 'screen_name' => 'user_name', 'count' => 200, 'max_id' => $last_id));
// loop through tweets and add to array
foreach($tweets as $t)
{
$tweets_to_process[] = $t;
}
// set prev and last id
$prev_id = $last_id;
$last_id = $tweets_to_process[count($tweets_to_process)-1]->id_str;
$loop_num ++;
}
正如您所看到的那样,我在while循环中放置了一个break计数器,因为从UX的角度来看,循环播放最多3200条推文的时间太长了。
答案 0 :(得分:2)
Twitter API的最新版本似乎专门用于减少每次从服务器中提取这些内容的持续压力。我建议你扩展你的代码以按时间(通过cron /计划任务)拉取twitter提要并在本地缓存时间轴条目。这样,您执行的操作可以更快地完成。
答案 1 :(得分:1)
扩展BAwebimax的建议..您可以定期下载并本地缓存推文,然后在用户登录时拨打超过'since_id / max_id'的新推文。 旧推文不会改变,因此您可以提前预处理这些推文。当用户登录您的应用时,这将导致更少的呼叫和更少的新推文处理。
...
刚刚注意到你的评论..如果场景涉及一次性使用且没有重复用户,则上述内容将无用。在这种情况下,你没有太多选择。
答案 2 :(得分:0)
在这种情况下,似乎不是一个更简化的解决方案。结束