I just started with Ruby and I am playing with Sinatra, but could not find a way to share database connections between requests.
I came from Java web developement and one of the basic things you have to do is to pool the database connections, so I am sure that something similar exists in Ruby, but I just can't find it.
ActiveRecord and DataMapper offer this feature but I don't need ORM and just want to make regular SQL queries.
Is there some specific approach for Sinatra or there are general ways for all Rack-based applications?
What is database connection pooling? Database connection pooling is a way to reduce the cost of opening and closing connections by maintaining a “pool” of open connections that can be passed from database operation to database operation as needed.
A connection pool synchronizes thread access to a limited number of database connections. The basic idea is that each thread checks out a database connection from the pool, uses that connection, and checks the connection back in.
pool is the config of size of connection pool, which is 5 by default. http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html. Follow this answer to receive notifications.
Create an instance of GenericObjectPoolConfig and set maximum idle, minimum idle and maximum connection properties. Now initialize ObjectPool using instances created in step 2 and step 3. Now set pool as an instance of PoolableConnectionFactory. Finally, initialize an instance of DataSource.
To persist a connection, you need only create an instance variable (Sinatra Applications are just objects anyway) or a global variable. Or a class that manages connections for you. Most Ruby database libraries I've seen are Database Adapters or just clients.
@db = Mysql2::Client.new #...
Or a global variable:
$db = Mysql2::Client.new #...
Connection pooling is just a way to share a small number of connections across multiple threads/fibers for the lifespan of the application. Java, the JVM, as far as I know doesn't share connections between processes.
However, there is a general purpose Connection Pool library for Ruby.
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