Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 935
Corey Trager Avatar asked Nov 20 '09 17:11

Corey Trager


2 Answers

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.

like image 100
rfunduk Avatar answered Oct 16 '22 00:10

rfunduk


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.

like image 23
Kyle Banker Avatar answered Oct 16 '22 00:10

Kyle Banker