Class: ConnectionPool
- Inherits:
-
Object
- Object
- ConnectionPool
- Defined in:
- lib/connection_pool.rb,
lib/connection_pool/version.rb
Overview
Generic connection pool class for e.g. sharing a limited number of network connections among many threads. Note: Connections are eager created.
Example usage with block (faster):
@pool = ConnectionPool.new { Redis.new }
@pool.with do |redis|
redis.lpop('my-list') if redis.llen('my-list') > 0
end
Example usage replacing an existing connection (slower):
$redis = ConnectionPool.wrap { Redis.new }
def do_work
$redis.lpop('my-list') if $redis.llen('my-list') > 0
end
Accepts the following options:
-
:size - number of connections to pool, defaults to 5
-
:timeout - amount of time to wait for a connection if none currently available, defaults to 5 seconds
Defined Under Namespace
Classes: Wrapper
Constant Summary collapse
- DEFAULTS =
{ :size => 5, :timeout => 5 }
- VERSION =
"0.9.1"
Class Method Summary collapse
Instance Method Summary collapse
- #checkin ⇒ Object
- #checkout ⇒ Object
-
#initialize(options = {}, &block) ⇒ ConnectionPool
constructor
A new instance of ConnectionPool.
- #with ⇒ Object (also: #with_connection)
Constructor Details
#initialize(options = {}, &block) ⇒ ConnectionPool
Returns a new instance of ConnectionPool.
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/connection_pool.rb', line 34 def initialize(={}, &block) raise ArgumentError, 'Connection pool requires a block' unless block = DEFAULTS.merge() @size = [:size] @timeout = [:timeout] @available = ::TimedQueue.new(@size, &block) @key = :"current-#{@available.object_id}" end |
Class Method Details
Instance Method Details
#checkin ⇒ Object
57 58 59 60 61 62 63 |
# File 'lib/connection_pool.rb', line 57 def checkin conn = ::Thread.current[@key] ::Thread.current[@key] = nil return unless conn @available << conn nil end |
#checkout ⇒ Object
53 54 55 |
# File 'lib/connection_pool.rb', line 53 def checkout ::Thread.current[@key] ||= @available.timed_pop(@timeout) end |
#with ⇒ Object Also known as: with_connection
46 47 48 49 50 |
# File 'lib/connection_pool.rb', line 46 def with yield checkout ensure checkin end |