如何正确停止和终止 Twitter4j 流 [英] how to stop and kill the Twitter4j stream correctly
问题描述
我尝试使用 Twitter4j 流媒体功能.所以我的实现是在以下类中:
I try to use the Twitter4j streaming features. So my implementation is in the following class :
public class TweetsStream {
private TwitterStream m_twitterstream;
private StatusListener m_statusListener;
public void printStream(...)
// Stream
m_twitterstream = null;
m_twitterstream = TwitterStreamFactory.getSingleton();
// Listener
m_statusListener = new StatusListenerRedefined(...);
m_twitterstream.addListener(m_statusListener);
// Filter
FilterQuery l_filter = new FilterQuery();
l_filter.track(... );
// Launch
m_twitterstream.filter(l_filter);
}
public void stopStream(){
m_twitterstream.shutdown();
m_logger.info("shutdown done");
m_twitterstream = null;
m_statusListener = null;
}
}
我的新 StatusListener() 在控制台中打印状态.
My new StatusListener() prints the status in the console.
然后我在另一个 servlet 类中创建一个 TweetsStream
对象:
Then I create a TweetsStream
object in another servlet class :
@WebServlet("/Controler")
public class Controler extends HttpServlet {
private static final long serialVersionUID = 1L;
// Logger
protected final static Logger m_logger = Logger.getLogger("Controler");
//Stream
private TweetsStream m_tweetStream;
//Function...
m_tweetStream = new TweetsStream(...);
m_tweetStream.printStream(...);
}
流工作完美.所以我现在试着阻止它.在同一个班级我有这个功能:
The stream works perfectly. So i try now to stop it. In the same class I have the function :
private void stopStream(){
m_tweetStream.stopStream();
m_tweetStream = null;
}
流在控制台停止,一切正常.
The stream is stopped in the console, all is fine.
但是当我在同一个班级回忆我的功能时:
BUT When I recall in the same class my function :
//Function...
m_tweetStream = new TweetsStream(...);
m_tweetStream.printStream(...);
就好像我刚刚恢复了先前的 m_twitterstream,并添加了一个侦听器.所以我每条推文都有两张印刷品...
It is as if i've just resume the previous m_twitterstream with one listener added. So I have two print of each tweet...
如何彻底杀死流?当我重新启动它时,怎么只有最后一个 StatusListener ?
How to kill completely the Stream ? And when I relaunch it, how only have the last StatusListener ?
谢谢!
推荐答案
解决方案如下:
方法 TwitterStreamFactory.getSingleton()
返回 TwitterStream 的相同实例.
The method TwitterStreamFactory.getSingleton()
returns the same instance of the TwitterStream.
即使您正确删除了 TwitterStream 对象,侦听器也会存储在您的 TwitterStream Singleton 配置中...因此您必须使用以下命令创建 TwitterStream 对象的不同实例:
Even if you delete properly your TwitterStream object, the listeners are stored in your TwitterStream Singleton config... So you have to create differents instances of the TwitterStream object with :
TwitterStreamFactory l_Twitterfactory = new TwitterStreamFactory();
m_twitterstream = l_Twitterfactory.getInstance();
这篇关于如何正确停止和终止 Twitter4j 流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!