java BlockingQueue和JDBC批处理更新
我正在寻找java并发解决方案,以便使用JDBC批处理更新。 BlockingQueue将允许我一次更新一个项目,我已经在DAO上有了批量更新的方法,但我需要一些解决方案,以便我可以利用JDBC批量更新而不是单记录更新 我的工作线程如下所示:java BlockingQueue和JDBC批处理更新,java,jdbc,concurrency,Java,Jdbc,Concurrency,我正在寻找java并发解决方案,以便使用JDBC批处理更新。 BlockingQueue将允许我一次更新一个项目,我已经在DAO上有了批量更新的方法,但我需要一些解决方案,以便我可以利用JDBC批量更新而不是单记录更新 我的工作线程如下所示: class DBWorker extends Thread { @Override public void run() { try { while (true) { t
class DBWorker extends Thread {
@Override
public void run() {
try {
while (true) {
try {
Pair<Long, Status> p = dbQ.take();
//--
orderDao.updateStatus(p.getLeft(), p.getRight());
} catch (InterruptedException e) {
log.error(e);
}
}
} catch (Exception e) {
log.error(e);
} finally {
}
}
}
基本上,您需要做的是将多个Pair对象收集到一个集合中,然后将该集合传递给将执行批处理更新的代码 您可以尝试以下方法:
while (true) {
Pair<Long, Status> p = dbQ.take();
List<Pair> collectedPairs = new ArrayList();
while (p!=null) {
collectedPairs.add(p);
p = dbQ.poll();
}
orderDao.batchUpdate(collectedPairs);
}
然而,上面的代码大多会以较小的大小发布批次。不过,您可以修改该示例,使用定时轮询方法BlockingQueue.pollllong,TimeUnit引入一些延迟,并尝试收集更大的批大小。基本上,您需要做的是将多个对对象收集到一个集合中,然后将该集合传递给将执行批更新的代码 您可以尝试以下方法:
while (true) {
Pair<Long, Status> p = dbQ.take();
List<Pair> collectedPairs = new ArrayList();
while (p!=null) {
collectedPairs.add(p);
p = dbQ.poll();
}
orderDao.batchUpdate(collectedPairs);
}
然而,上面的代码大多会以较小的大小发布批次。不过,您可以修改该示例,使用计时轮询方法BlockingQueue.polllong,TimeUnit引入一些延迟,并尝试收集更大的批处理大小。BlockingQueue有一个很好的方法,drainTo基本上接收所有条目并将其放入一个集合中。虽然它没有阻塞,所以在调用它之前,您仍然需要进行一次拍摄,这样它就不会有繁忙的等待。您还需要一种批量更新数据库的方法,而不是更新一和一。例如:
ArrayList<Pair<Long, Status>> list = new ArrayList<Pair<Long, Status>>();
list.add(dbQ.take());
//sleep(int n) - if you want to wait for more entries before submitting the batch - otherwise batches will probably be pretty small..
dbQ.drainTo(list);
orderDao.updateInBatch(list);
BlockingQueue有一个很好的方法,drainTo基本上会获取所有条目并将其放入一个集合中。虽然它没有阻塞,所以在调用它之前,您仍然需要进行一次拍摄,这样它就不会有繁忙的等待。您还需要一种批量更新数据库的方法,而不是更新一和一。例如:
ArrayList<Pair<Long, Status>> list = new ArrayList<Pair<Long, Status>>();
list.add(dbQ.take());
//sleep(int n) - if you want to wait for more entries before submitting the batch - otherwise batches will probably be pretty small..
dbQ.drainTo(list);
orderDao.updateInBatch(list);
+我经常忘记那个好方法。我经常忘记那个好方法。