2011-09-28 9 views
5

ruby​​でoplogウォッチャーを作成しようとしています。今のところ、以下の小さなスクリプトが出てきます。mongo dbのタイムアウトにカーソルがある

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 

エラーを取得するときイムことができます実際のデータを見るにはどうすれば突然カーソルが見つからないと言うことができますか?私はルビーにはかなり新しく、私はどの方向性を取らなければならないかについてのアイデアは私には役に立ちます。

答えて

5

解決策は、カーソルが1秒あたりの書き込み回数が多い比較的小さな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-user googleグループに感謝します。