Twitter流API - 限制推文数量

时间:2014-06-03 13:13:35

标签: twitter twitter4j twitter-streaming-api

我可以使用下面的推特流API来获取实时推特流

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey("xxxx");
    cb.setOAuthConsumerSecret("xxxx");
    cb.setOAuthAccessToken("xxxx");
    cb.setOAuthAccessTokenSecret("xx");
    int count = 0;
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener = new StatusListener() {


        public void onStatus(Status status) {

            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
           // count++;
        }


        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }
    };

    FilterQuery fq = new FilterQuery();
    String keywords[] = {"samsung"};
    String lang[] = {"en"};
    fq.track(keywords);
    fq.language(lang);
    twitterStream.addListener(listener);
    twitterStream.filter(fq);   

如何限制推文的数量?上述程序无限期运行。如何在获得所需数量的推文后停止该程序?

1 个答案:

答案 0 :(得分:0)

限制将推文存储在例如LinkedBlockingQueue

private LinkedBlockingQueue<Status> tweets = new LinkedBlockingQueue<>(10000);

StatusListener listener = new StatusListener() {

@Override
public void onStatus(Status status) {
    tweets.add(status);
}

您可以稍后使用Status message = obrada.poll();在foreach循环中对其进行检索。 ....或者只是创建计数器并询问常规ArrayList的大小 -

  

if(tweets.size()&gt; = 1000)twitterStream.shutdown(); twitterStream.cleanUp();