如何使用 twitter4j 处理速率限制?

How to handle rate limit using twitter4j?

我经常使用 twitter4j 遇到以下异常:

2015-06-02 10:04:30,802 DEBUG [Twitter Stream consumer-1[Establishing connection]] TwitterBot(116): Got an exception 420:Returned by the Search and Trends API when you are being rate limited (https://dev.twitter.com/docs/rate-limiting).
Returned by the Streaming API:
 Too many login attempts in a short period of time.
 Running too many copies of the same application authenticating with the same account name.
Exceeded connection limit for user

因为我尽量避免被 Twitter 禁止,所以我想问一下,如果我的代码做错了什么:

我在 Stream API 上使用 StatusListener,它由我自己的 ID 和一些字符串值过滤。

如果状态符合条件,则会通过 Twitter 发送对此状态的回答。这种情况不会经常发生,因此这不应该是速率限制异常的问题。

整个过程都在 TomEE EJB 环境中运行,这是否重要?

@Startup
@Singleton
public class TwitterBot implements Service {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TwitterBot.class);

    //this is fix for this twitter bot
    public static final String TWITTER_BOT_NAME = "botname";
    public static final long TWITTER_BOT_USER_ID = 99999L; //the bot's user id

    private final TwitterStream twitterStream;
    private final Twitter twitter;

    public TwitterBot() {

        this.twitterStream = new TwitterStreamFactory().getInstance();
        this.twitter = TwitterFactory.getSingleton();
    }


    @PostConstruct
    public void listen() {

        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {

                //this is to avoid a circle... ignore tweets coming from ourselves.
                if (status.getUser().getScreenName().equalsIgnoreCase(TWITTER_BOT_NAME)) {
                    return;
                }

                try {

                    //do something and update own status

                    StatusUpdate update = new StatusUpdate("Hello World!");
                    update.setInReplyToStatusId(status.getId());

                    twitter.updateStatus(update);

                } catch (TwitterException e) {
                    logger.error("Could not complete twitter update, {}", e.getLocalizedMessage(), e);
                }

            }

           //other Status Listener methods, which are not used (default implementation)
        };

        //filtering for ourselves here
        long[] userFilter = {TWITTER_BOT_USER_ID};

        String[] termFilter = {TWITTER_EXPERTIZER_BOT_NAME};

        FilterQuery filter = new FilterQuery(0, userFilter, termFilter);

        twitterStream.addListener(listener);

        twitterStream.filter(filter);

    }
}

这个 How to handle rate limit using twitter4j to avoid being banned 的答案告诉我,Streaming API 没有速率限制。

所以问题是什么? API 文档中有解释吗?

提前致谢!

编辑:

问题与

有关
FilterQuery filter = new FilterQuery(0, userFilter, termFilter);

像这样使用查询会在 Twitter API 上产生某种轮询,因此会超出连接限制。

改为使用:

 FilterQuery filter = new FilterQuery(termFilter);