【问题标题】:Inserting 200k records while parsing CSV locks up system解析 CSV 时插入 20 万条记录会锁定系统
【发布时间】:2012-05-28 15:08:00
【问题描述】:

我正在尝试将 20 万条记录插入三个不同的表中。当我解析 CSV 文件并尝试插入这些记录时,Ruby 锁定了我的整个系统。这是我的代码:

def upload_country
  @upload = Upload.new(:upload => params[:upload])
  if  @upload.save
  csv = CSV.parse(csv_text, :headers => true)

  csv.each_with_index do |row, index|
    unless row["name"].blank? or row["country_code"].blank? or row["destination"].blank? or row["code"].blank?
      @country = Country.new(:name => row["name"].gsub(/\s+/, " ").strip, :country_code => row["country_code"].gsub(/\s+/, " ").strip, :user_id => current_user.id, :subscriber_id => get_subscriber_id)
      @country.save

      if row["country_code"] == "1"
        p = @country.country_code.to_s+@destination.name+row["code"].gsub(/\s+/, " ").strip
      else
        p = @country.country_code.to_s+row["code"].gsub(/\s+/, " ").strip
      end

      @code = DestinationCode.create(:code => p, :country_destination_id => 1, :user_id => current_user.id)
    end
  end

  @upload.destroy
  @countries = Country.find_all_by_subscriber_id(get_subscriber_id)
  render :partial => '/mycarriers/carrier_country', :layout => false
end

【问题讨论】:

  • 请求需要很长时间才能执行?创建 200k 个对象并插入它们可能不是那么快。您可能应该以某种方式批量插入。
  • @kashifali:你让它运行了多长时间?

标签: ruby-on-rails ruby activerecord csv


【解决方案1】:

如果您有长时间运行的请求,这意味着如果您只有一个 Rails 实例正在运行,那么届时其他用户将无法访问您的应用程序。

我建议你使用delayed_job gem 在后台做长时间的处理任务。在控制器端,您应该将作业和response 202 (Accepted) 排入浏览器。在客户端,无论作业是否完成,您都应该定期向服务器发送请求。然后,相应地更新 ui。

slideshare.net 为例。当用户完成上传后,slideshare 重定向到新页面,并在转换演示文件时定期更新 ui。

另一种解决方案是您可以在后台运行 rake 脚本。从 railscasts 查看this episode

【讨论】:

    【解决方案2】:

    为什么不在这里使用 Mass Insert 一个 gem,它可以帮助你完成我个人在我的应用程序中使用它来插入 500K 记录和resque 用于后台处理

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2011-09-21
      • 2016-01-11
      • 1970-01-01
      • 2023-01-31
      • 2018-02-08
      • 2012-09-09
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多