我目前正在实现一个程序,该程序要求我使用 Twitter4J 来收集推文并存储它们。然而,我确实意识到使用 Twitter 的开发者 API 每 15 分钟只能发出 180 个请求。
因此,我创建了一种方法,在程序收到 10 条推文后停止程序 15 分钟,同时我的消费者和访问 key 重置速率限制。然而,有时在获取这 10 条推文之间,速率限制仍然会耗尽?所以我想做的是改变方法,使其因速率限制即将耗尽而停止。
例如...
if (rate limit = 0){
stop program until rate limit resets
}
但是,我刚才的方法只是实现了一个计数器,当计数器达到 10 时,它就会停止,这不是很经济或有效。我认为 10 条推文就足够了,但显然不够。 这是我的方法...
public void getRateLimit() throws TwitterException{
if (count == 10){
try {
System.out.println("Rate Limit is about to be exhausted for resource...");
System.out.println("Please wait for 15 minutes, while it resets...");
TimeUnit.MINUTES.sleep(15);
count = 0;
} catch (InterruptedException e) {
System.out.println(e);
}
}
我怎样才能改变它,以便它在速率限制即将用完时耗尽并停止,并且仅在补充时才开始。 感谢您的帮助。
最佳答案
我之前遇到过同样的问题,我尝试计算 1 个请求所花费的时间。如果该请求少于 5500 毫秒,则程序会等待 5500 毫秒,并且它对我来说完美工作,
你可以问为什么是 5500 毫秒,因为 15 分钟 180 个请求使得每个请求 5 秒。
这是我使用的代码,希望对您有所帮助。
do {
final long startTime = System.nanoTime();
result = twitter.search(query);
statuses = result.getTweets();
for (Status status : statuses) {
tweet = new Tweet(status);
userProfile = new UserProfile(status.getUser());
imageDownloader.getMedia(tweet.mediaEntities);
imageDownloader.getProfilePhoto(userProfile.ProfileImageUrl);
System.out.println(tweet);
System.out.println(userProfile);
}
final long duration = System.nanoTime() - startTime;
if ((5500 - duration / 1000000) > 0) {
logger.info("Sleep for " + (6000 - duration / 1000000) + " miliseconds");
Thread.sleep((5500 - duration / 1000000));
}
} while ((query = result.nextQuery()) != null);
关于java - 速率限制预防 [Twitter4J],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35760269/