gpt4 book ai didi

Grails 批量插入/更新优化

转载 作者:行者123 更新时间:2023-12-02 14:23:16 24 4
gpt4 key购买 nike

我正在从 csv 文件中导入大量数据,(文件大小超过 100MB)

我正在使用的代码如下所示:

    def errorLignes = []
def index = 1
csvFile.toCsvReader(['charset':'UTF-8']).eachLine { tokens ->
if (index % 100 == 0) cleanUpGorm()
index++

def order = Orders.findByReferenceAndOrganization(tokens[0],organization)

if (!order) {
order = new Orders()

}

if (tokens[1]){
def user = User.findByReferenceAndOrganization(tokens[1],organization)
if (user){
order.user = user
}else{
errorLignes.add(tokens)
}
}

if (tokens[2]){
def customer = Customer.findByCustomCodeAndOrganization(tokens[2],organization)
if (customer){
order.customer = customer
}else{
errorLignes.add(tokens)
}
}


if (tokens[3]){
order.orderType = Integer.parseInt(tokens[3])
}
// etc.....................
order.save()

}

我使用 cleanUpGorm 方法在每 100 个条目后清理 session
def cleanUpGorm() {
println "clean up gorm"
def session = sessionFactory.currentSession
session.flush()
session.clear()
propertyInstanceMap.get().clear()
}

我还关闭了二级缓存
hibernate {
cache.use_second_level_cache = false
cache.use_query_cache = false
cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
}

项目的 grails 版本是 2.0.4,作为数据库,我使用的是 mysql

对于每个条目,我都会调用 3 次查找
  • 检查订单是否已经存在
  • 检查用户是否正确
  • 检查客户是否正确

  • 最后我保存了订单实例

    导入过程太慢,我想知道如何加快和优化这段代码。

    编辑 :

    我发现可搜索插件也让它变慢了。
    所以,为了解决这个问题,我使用了以下命令:
    searchableService.stopMirroring()

    但它仍然不够快,我终于将代码更改为使用 groovy sql

    最佳答案

    这发现此博客条目非常有用:
    http://naleid.com/blog/2009/10/01/batch-import-performance-with-grails-and-mysql/

    您已经在清理 GORM,但请尝试每 100 个条目清理一次:

    def propertyInstanceMap = org.codehaus.groovy.grails.plugins.DomainClassGrailsPlugin.PROPERTY_INSTANCE_MAP
    propertyInstanceMap.get().clear()

    创建数据库索引也可能有所帮助并使用 default-storage-engine=innodb而不是 MyISAM .

    关于Grails 批量插入/更新优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28875150/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com