mmcgrana / connection_pool

ORM-agnostic persistent connection pooling for Ruby

This URL has Read+Write access

mmcgrana (author)
Tue Aug 19 18:13:11 -0700 2008
commit  afb742ddf49333f7b34bb876da3135e5fdf26200
tree    a66a66a3865d23ed3bd1c2df169d9a868204b10f
parent  cd6a56ee2dd07a210a3672a25eda46cd93392aa3
name age message
file README.textile Thu Jul 24 06:45:45 -0700 2008 not just for databases anymore... [mmcgrana]
file connection_pool.gemspec Thu Jul 24 06:48:26 -0700 2008 gemspec [mmcgrana]
directory dev/ Thu Jul 24 06:45:21 -0700 2008 normalize whitespace [mmcgrana]
directory lib/ Tue Aug 19 18:13:11 -0700 2008 remove unused block var [mmcgrana]
directory spec/ Thu Jul 24 06:45:21 -0700 2008 normalize whitespace [mmcgrana]
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