Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

ORM-agnostic persistent connection pooling for Ruby

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 dev
Octocat-spinner-32 lib
Octocat-spinner-32 spec
Octocat-spinner-32 README.textile
Octocat-spinner-32 connection_pool.gemspec
README.textile

ConnectionPool

ORM-agnostic persistent connection pooling for Ruby

Credit

Extracted from the Sequel and DataMapper libraries.

Usage

To create a connection pool, tell ConnectionPool how many connections you want to allow in the pool, how to open connections, and how to close connections.


  pool =
    ConnectionPool.new(
      10,
      Proc.new { MyConnection.new({:port => 4000}) },
      Proc.new { |conn| conn.close })

Use #lease_connection to get a connection from the pool. A connection can be leased by only one thread at a time. The connection is released back into the pool when the block closes.


  pool.lease_connection do |conn|
    conn.execute("SELECT * FROM users")
  end
  #=> (result of #execute)

Leasing is handled as follows: If the pool has free connections, the pool yields the calling thread one of them. If the pool does not have any free connections but the pool still has room to expand, the pool creates a new connection using the block given as the second argument to the constructor. If the pool is full and all connections are being used, the #lease_connection call blocks until a connection is freed by another thread.

The call to #lease_connection is re-entrant, so you can lease a connection from within another lease block and get the same connection:


  pool.lease_connection do |conn_outer|
    pool.lease_connection do |conn_inner|
      conn_outer == conn_inner
      # true
    end
  end
Something went wrong with that request. Please try again.