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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With