views:

2142

answers:

3

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
A: 

Here's a pretty good example app using Sinatra and MongoDB - probably can get a good start from looking at that code.

mdirolf
When I do what you do and look at the output of mongod, I see connections being made for each HTTP request, including requests for css, js files.
Corey Trager
A: 

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.

Kyle Banker
I think I'm doing what you suggest, but it's not behaving as you say.
Corey Trager
See "EDIT1" in my question as an example of what is NOT working.
Corey Trager
+2  A: 

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.

thenduks