出于某种原因,我们计划在我们的项目中使用红隼队列。我们做了一些恶魔,主要问题是如何有效地从 CPU 利用率低的队列中获取数据。我们实现获取的方式是,如果我们从队列中获取数据失败超过 5 次,我们将线程休眠 100 毫秒以降低 CPU 利用率。
while (running) {
try {
LoginLogQueueEntry data = kestrelQueue.fetch();
if (null != data && data.isLegal()) {
entryCacheList.add(data); //add the data to the local caceh
resetStatus();
} else {
failedCount++;
//if there is no data in the kestrel and the local cache is not empty, insert the data into mysql database
if (failedCount == 1 && !entryCacheList.isEmpty()) {
resetStatus();
insertLogList(entryCacheList); // insert current data into database
entryCacheList.clear(); //empty local cache
}
if (failedCount >= 5 && entryCacheList.isEmpty()) {
//fail 5 times. Sleep current thread.
failedCount = 0;
Thread.sleep((sleepTime + MIN_SLEEP_TIME) % MAX_SLEEP_TIME);
}
}
//Insert 1000 rows once
if (entryCacheList.size() >= 1000) {
insertLogList(entryCacheList);
entryCacheList.clear();
}
} catch (Exception e) {
logger.warn(e.getMessage());
}
有没有其他好的方法可以做到这一点?我认为完美的方式是队列可以通知工作人员我们得到数据并获取它们。