2
經過幾千條推文後,我的應用程序從Twitter API中收集推文,Twitter4J得到一個OutOfMemory錯誤。如何通過Twitter4J streaming API避免OutOfMemory錯誤?
在接收狀態時,我的代碼會:
- 將狀態轉換爲我自己的對象TwitterStatus
。原因是Twitter4J返回的Status
是一個接口,不能在MongoDB中序列化。
- 將此狀態添加到列表中。
- 如果列表大小大於25或100(取決於tweet的接收速度),則保存到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);
}
}
}
你知道大約每秒鐘有多少鳴叫嗎? –
我過濾關鍵字「twitter」上的流,這非常頻繁。我不確定,但是每秒鐘大概有10條推文,我會說。這也會產生很多失速警告(但在這裏並不相關?) – seinecle
我不知道是否屬於這種情況,但根據我的經驗,當聽衆獲得比應用程序能夠處理的更多推文時會出現此錯誤。 –