Corey Trager
Corey Trager

Reputation: 23141

Using Sinatra and MongoDB - what's the recommended way to "keep alive" the mongodb connection between http requests?

I've used ASP.NET and now I'm working on a Sinatra/MongoDB app. With ASP.NET architecture, the connection to the database a given request uses comes from a pool of connections that the ADO.NET manages. The connections are kept alive in the pool between requests so that the cost of building and tearing down the connection isn't paid for each http request.

Is there a similar mechanism in a Sinatra MongoDB app, or will I need to connect/disconnect with each request? If there is a mechanism, what does the code look like?

EDIT1: The following does NOT work. Each HTTP request that the browser sends hits the new.db line, including requests for css, js, jpeg files.

require 'mongo'
include Mongo

db = Mongo::Connection.new.db("MyDb")

class MyApp < Sinatra::Base
    get '/' do
       etc

Upvotes: 11

Views: 8878

Answers (2)

Kyle Banker
Kyle Banker

Reputation: 4359

If you create your database connection outside of the scope of the request methods, the connection won't be reinstantiated at each request.

You might want to try using a global or instance variable when you initialize the db.

# Should be in a configure block
configure do
  DB = Connection.new.db('test-sinatra')
end

Also, connection pooling is not the issue here, and certainly isn't the solution to this particular problem.

Upvotes: 6

rfunduk
rfunduk

Reputation: 30442

The newest version of the ruby mongodb driver includes connection pooling. You could set up your pool in your configure block in your sinatra app and Bob's your uncle.

Upvotes: 8

Related Questions