加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 使用SaxMachine解析大文件似乎是将整个文件加载到内存中

发布时间:2020-12-17 03:35:34 所属栏目:百科 来源:网络整理
导读:我有一个1.6GB的xml文件,当我用Sax Machine解析它时,它似乎不是流式传输或以块的形式吃掉文件 – 而是它似乎将整个文件加载到内存中(或者可能在某处存在内存泄漏) ?)因为我的ruby过程爬上了2.5gb的ram.我不知道它在哪里停止增长,因为我的内存不足. 在较小的
我有一个1.6GB的xml文件,当我用Sax Machine解析它时,它似乎不是流式传输或以块的形式吃掉文件 – 而是它似乎将整个文件加载到内存中(或者可能在某处存在内存泄漏) ?)因为我的ruby过程爬上了2.5gb的ram.我不知道它在哪里停止增长,因为我的内存不足.

在较小的文件(50mb)上,它似乎也在加载整个文件.我的任务迭代xml文件中的记录并将每个记录保存到数据库.它需要大约30秒的“空闲”,然后数据库查询突然开始执行.

我认为SAX应该允许你使用这样的大文件,而不会将整个内容加载到内存中.

有什么我可以忽略的吗?

非常感谢

更新以添加代码示例

class FeedImporter

  class FeedListing
    include ::SAXMachine

    element :id
    element :title
    element :description
    element :url

    def to_hash
      {}.tap do |hash|
        self.class.column_names.each do |key|
          hash[key] = send(key)
        end
      end
    end
  end

  class Feed
    include ::SAXMachine
    elements :listing,:as => :listings,:class => FeedListing
  end

  def perform
    open('~/feeds/large_feed.xml') do |file|

      # I think that SAXMachine is trying to load All of the listing elements into this one ruby object.
      puts 'Parsing'
      feed = Feed.parse(file)

      # We are now iterating over each of the listing elements,but they have been "parsed" from the feed already.
      puts 'Importing'
      feed.listings.each do |listing|
        Listing.import(listing.to_hash)
      end

    end
  end

end

如您所见,我不关心< listing> Feed中的元素.我只想要每个< listing>的属性元件.

输出如下所示:

Parsing
... wait forever
Importing (actually,I don't ever see this on the big file (1.6gb) because too much memory is used :(

解决方法

我分叉了sax-machine以便它使用恒定的内存: https://github.com/gregwebs/sax-machine

好消息:有一位新的维护者正在计划合并我的更改.我自己和新的维护者已经使用我的叉子一年没问题了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读