使用grails批量处理数百万个DB记录

时间:2013-12-11 10:54:31

标签: mysql grails concurrency

我需要帮助使用grails处理数百万个db记录。

我在db中有数百万条记录。我不能在单个查询中获取所有记录,因为它会抛出内存异常。所以我想分批获取记录。并处理每批的每条记录。 我想在grails中使用Blocking Queue类实现,我将在队列中添加所有子查询的结果,然后多个线程将使用队列并进行自己的处理。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

这可能不是您想要的有效解决方案,但是,使用 bootstarp.groovy文件我处理类似的问题,例如从excel文件读取并将其添加到数据库中,每个记录使用线程逐行获取。

import grails.transaction.Transactional;

BootStrap.groovy

@Transactional
def importformExcel(){

// add you code here for batching...and call it inside the thread
}

bootstrap.init部分中添加以下代码以在启动时执行它。您可以添加一些逻辑以防止每次运行或使其一旦执行并永久停止。

  def init = { servletContext ->

        sessionFactory.currentSession.flush()
        try{
                    @Transactional
                    Thread stateLgaThread = new Thread({

                     //code ur thread logic here!
                     importformExcel()
                     //sessionFactory.currentSession.flush()
                     TimerThread.sleep(100) // even give more chance to other application/instruction
                     } as Runnable).start()
                     @Transactional
                     Thread regionThread = new Thread({
                        //code ur thread logic here!
                        importformExcel()
                        // sessionFactory.currentSession.flush()
                         TimerThread.sleep(100) // even give more chance to other application/instruction
                     } as Runnable).start()
                }
                catch(ex){

                    log.debug "Inside Thread Exception:{ex.message}"
                }

}