Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

database connection pooling in ruby

Tags:

ruby

sinatra

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?

like image 980
Nikoi Avatar asked Aug 16 '12 18:08

Nikoi


People also ask

What is pooling in database connection?

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.

What is connection pool in rails?

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.

What is pool in database Yml?

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.

How do I create a database connection pool?

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.


1 Answers

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.

like image 190
Robert K Avatar answered Sep 17 '22 21:09

Robert K