我正在尝试将Sample Stream中的推文存储到数据库中并同时存储原始json。我在hbc Github存储库中的example之后使用Twitter4jStatusClient
。由于我只是实时将一部分信息存储到数据库中,我希望也能存储推文的原始json,这样我就可以在需要时检索其他信息。但是,使用Twitter4jStatusClient
意味着侦听器在不同的线程上执行,而在here中,它表示为了获取json对象,它必须从检索json对象的同一线程执行。有没有办法在使用Twitter4JStatusClient
时保存json字符串?我选择不使用此example因为我只想执行某些操作并保存json字符串(如果它是状态)。谢谢!
// Create an appropriately sized blocking queue
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
// Define our endpoint: By default, delimited=length is set (we need this for our processor)
// and stall warnings are on.
StatusesSampleEndpoint endpoint = new StatusesSampleEndpoint();
// Specify the language filter for the endpoint
endpoint.addQueryParameter(Constants.LANGUAGE_PARAM, Joiner.on(',').join(Lists.newArrayList("en")));
endpoint.stallWarnings(false);
Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
// Create a new BasicClient. By default gzip is enabled.
BasicClient client = new ClientBuilder()
.name("sampleStreamClient")
.hosts(Constants.STREAM_HOST)
.endpoint(endpoint)
.authentication(auth)
.processor(new StringDelimitedProcessor(queue))
.build();
// Create an executor service which will spawn threads to do the actual work of parsing the incoming messages and
// calling the listeners on each message
int numProcessingThreads = 4;
ExecutorService service = Executors.newFixedThreadPool(numProcessingThreads);
StatusListener listener = new SampleStreamStatusListener(jsonInserter);
// Wrap our BasicClient with the twitter4j client
t4jClient = new Twitter4jStatusClient(
client, queue, Lists.newArrayList(listener), service);
答案 0 :(得分:0)
我在Twitter4jStatusClient
遇到了类似的问题,这里有一些想法
中间队列
你可以有一个单独的线程池,它从你的queue
变量中读取原始消息,将它们存储在某个地方,然后将它们放入我们称之为hbcQueue
的新队列中,然后将其传递给Twitter4jStatusClient
构造函数而不是queue
。
BlockingQueue<String> hbcQueue = new LinkedBlockingQueue<>(10000);
ExecutorService rawJsonSaver = Executors.newFixedThreadPool(numProcessingThreads);
for (int i = 0; i < numProcessingThreads; i++) {
rawJsonSaver.execute(() -> {
for (;;) {
try {
String msg = queue.take();
JSONObject jobj = new JSONObject(msg);
if (JSONObjectType.determine(jobj) == JSONObjectType.Type.STATUS) {
System.out.println(msg); // Save it
hbcQueue.add(msg);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); break;
} catch (JSONException e) {
continue;
}
}
});
}
Twitter4jStatusClient t4jClient = new Twitter4jStatusClient(
client, hbcQueue, Lists.newArrayList(listener), service);
但是,当然这有第二次解析JSON并为第二个并发队列添加另一个阻塞锁操作的性能缺点。
<强>重新序列化强>
如果您稍后要在Java中处理原始JSON,则可以使用纯Java序列化,因为传递给Status
的{{1}}对象实现了StatusListener
。这不是将其重新序列化为JSON的延伸,但至少您不需要手动序列化每个字段。
Serializable