java - 速率限制预防 [Twitter4J]

标签 java twitter twitter4j rate-limiting

我目前正在实现一个程序,该程序要求我使用 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/

相关文章:

iphone - iOS SLComposeViewController - 不显示推特帖子的网址

java - 如何解释我的 twitter4J 错误?

java - 如果输入与数组列表中的数字匹配,则无法获取方法 (getTest) 返回 true boolean 方法结果

iOS (iPhone/iPad) SDK - 将 JSON 解析器与 Twitter 的 user_timeline 结合使用

node.js - Node Red 调试 Node 在 Bluemix 中不工作

java - 使用 Twitter4j API 获取 friend 的时间线

java - Twitter4J get Direct Messages() 不再起作用了吗?

java - hibernate 关系: Column 'purchaseId' cannot be null

java - Maven 取消禁止依赖项(为了使用库)?

java - 关闭/打开连接是否违反不变性?