mongodb中的tailable游标超时

时间:2011-09-28 07:08:13

标签: ruby mongodb

我正在尝试在ruby中创建一个oplog观察器。到目前为止,我已经在下面提出了一个小脚本。

require 'rubygems'
require 'mongo'
db = Mongo::Connection.new("localhost", 5151).db("local")
coll = db.collection('oplog.$main')

loop do
cursor = Mongo::Cursor.new(coll, :tailable => true)
    while not cursor.closed?
        if doc = cursor.next_document
            puts doc
        else
            sleep 1
        end
    end
end

问题是,在5或6秒后吐出大量数据时会超时并出现错误

C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/connection.rb
:807:in `check_response_flags': Query response returned CURSOR_NOT_FOUND. Either an invalid c
ursor was specified, or the cursor may have timed out on the server. (Mongo::OperationFailure
)
        from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/
connection.rb:800:in `receive_response_header'
        from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/
connection.rb:768:in `receive'
        from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/
connection.rb:493:in `receive_message'
        from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/
connection.rb:491:in `synchronize'
        from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/
connection.rb:491:in `receive_message'
        from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/
cursor.rb:494:in `send_get_more'
        from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/
cursor.rb:456:in `refresh'
        from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/
cursor.rb:124:in `next_document'
        from n.rb:7
        from n.rb:6:in `loop'
        from n.rb:6

我不明白的是,当我能够看到实际数据时,它怎么会突然说光标找不到。我对红宝石很新,我必须采取的任何方向对我都有用。

1 个答案:

答案 0 :(得分:5)

解决方案是我需要有一个异常处理机制来捕获当游标在每秒写入次数较多的相对较小的oplog中读取最后一个文档时引发的异常。由于游标到达oplog的末尾,因此会抛出一个没有更多记录的异常。

require 'rubygems'
require 'mongo'
db = Mongo::Connection.new("localhost",5151).db("local")
coll = db.collection('oplog.$main')
loop do
cursor = Mongo::Cursor.new(coll, :timeout => false, :tailable => true)
    while not cursor.closed?
    begin
      if doc = cursor.next_document   
          puts "Timestamp"
          puts  doc["ts"]
          puts "Record"
          puts  doc["o"]
          puts "Affected Collection"
          puts doc["ns"]
      end
    rescue
        puts ""
        break
    end
  end
end

现在可以处理异常。感谢mongodb用户谷歌小组向我指出这一点。