kgaekwad
kgaekwad

Reputation: 53

Using Sinatra and MongoDB- Closing connections?

Do I need to free/close pooled mongodb connections in Ruby and Sinatra? I looked at http://api.mongodb.org/ruby/current/#Connection_Pooling but didn't see anything specific in there.

However, every now and then I get this error for a relatively low traffic application:

Error in the smoke test block could not obtain connection within 10 seconds. The max pool size is currently 10; consider increasing the pool size or timeout.: ["/var/lib/gems/1.9.1/gems/mongo-1.9.1/lib/mongo/util/pool.rb:274:in `block in checkout'",

I currently use a configure block to set up the connection:

configure do
 #Reading the file
 ini = IniFile.new(:filename=>file_name,:parameter => '=')
    section = ini['server']
 env = section['environment']
 mongoip = section['mongo_host']
 mongo_port = section['mongo_port']
 $environment = section['environment']

 begin
   $mongo_client =  MongoClient.new(mongoip, mongo_port, :pool_size => 10, :pool_timeout => 10,:connect_timeout =>10)
 rescue Exception => e
   "Error connecting to the database"
 end
end

What am I missing here?

Upvotes: 2

Views: 771

Answers (1)

Gautam Rege
Gautam Rege

Reputation: 697

Note from the future: While this may have been true at the time, Moped is no longer actively developed and both the former Moped developers and the MongoClient developers now working actively on MongoClient.


I would strongly suggest using Moped instead of MongoClient (which is really old and has lots of dependencies).

Moped automatically handles the connection pool, timeouts, reconnects and is smart. You can find details specifically about the connection pool at https://github.com/mongoid/moped/blob/master/lib/moped/connection/pool.rb

Moped is a stand-alone gem with no dependencies and is a pure Ruby driver for MongoDB. http://mongoid.org/en/moped/

While your're at it, use Origin another standalone gem that exposes an excellent DSL for MongoDB queries.

Upvotes: 1

Related Questions