![](/img/trans.png)
[英]How to retrieve all the tweets of my followers through the twitter streaming API with twitter4J?
[英]How to avoid OutOfMemory error with Twitter4J streaming API?
經過數千次推文后,我的應用程序使用Twitter4J從流API收集推文時,收到OutOfMemory錯誤。
收到狀態后,我的代碼執行以下操作:
-將狀態轉換為我自己的TwitterStatus
對象。 原因是Twitter4J返回的Status
是一個接口,無法在MongoDB中序列化。
-將此狀態添加到列表中。
-如果列表的大小大於25或100(取決於推文的接收速度),則保存到db。
因此,這非常簡單,我沒有在本地存儲任何內容,但是卻收到此OutOfMemory錯誤。 有什么線索可以降低內存占用量嗎?
編碼:
StatusListener listener;
listener = new StatusListener() {
@Override
public void onStatus(Status status) {
nbTweets++;
//the Status returned by Twitter4j is an interface, not serializable. I convert it into my own TwitterStatus object: same fields, serializable.
twitterStatus = convertStatus.convertOneToTwitterStatus(status);
twitterStatus.setJobId(jobUUID);
twitterStatuses.add(twitterStatus);
statusesIds.add(status.getId());
timeSinceLastStatus = System.currentTimeMillis() - timeLastStatus;
//**************************************
//adjusting the frequency of saves to DB, function of number of statuses received per second
if (timeSinceLastStatus < 200) {
sizeBatch = 100;
} else {
sizeBatch = 25;
}
timeLastStatus = System.currentTimeMillis();
progressLong = (Long) ((System.currentTimeMillis() - startDateTime.getMillis()) * 100 / (stopTime - startDateTime.getMillis()));
if (statusesIds.size() > sizeBatch || progressLong.intValue() > progress) {
//**************************************
//saving statuses to the db.
dsTweets.save(twitterStatuses);
twitterStatuses = new ArrayList();
//**************************************
//updating list of status ids of the job.
opsJob = dsJobs.createUpdateOperations(Job.class).addAll("statuses", statusesIds, true);
dsJobs.update(updateQueryJob, opsJob);
statusesIds = new ArrayList();
//updating progress.
System.out.println("progress: " + progressLong);
progress = progressLong.intValue();
opsJobInfo = dsJobsInfo.createUpdateOperations(JobInfo.class).set("progress", progress).set("nbTweets", nbTweets);
dsJobsInfo.update(updateQueryJobInfo, opsJobInfo);
}
}
}
得到它了。
從2.6版開始, MongoDB的默認寫關注點是“ acknowledge” ,而不是未確認的。 這大大降低了操作速度。
只需將WriteConcern.UNACKNOWLEDGED
添加到所有數據庫寫入操作即可解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.