2011-09-19 17:29:59 -04:00
|
|
|
require 'timed_queue'
|
2011-05-14 15:29:51 -04:00
|
|
|
|
|
|
|
# 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|
|
2011-05-14 18:36:17 -04:00
|
|
|
# redis.lpop('my-list') if redis.llen('my-list') > 0
|
2011-05-14 15:29:51 -04:00
|
|
|
# end
|
|
|
|
#
|
|
|
|
# Example usage replacing a global connection (slower):
|
|
|
|
#
|
|
|
|
# REDIS = ConnectionPool.new { Redis.new }
|
|
|
|
#
|
|
|
|
# def do_work
|
2011-05-14 18:36:17 -04:00
|
|
|
# REDIS.lpop('my-list') if REDIS.llen('my-list') > 0
|
2011-05-14 15:29:51 -04:00
|
|
|
# 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
|
|
|
|
#
|
2011-09-19 13:29:31 -04:00
|
|
|
class ConnectionPool < BasicObject
|
2011-05-14 15:29:51 -04:00
|
|
|
DEFAULTS = { :size => 5, :timeout => 5 }
|
|
|
|
|
2011-09-19 13:29:31 -04:00
|
|
|
def initialize(options={}, &block)
|
|
|
|
::Kernel.raise ::ArgumentError, 'Connection pool requires a block' unless block
|
2011-09-18 16:26:26 -04:00
|
|
|
|
2011-09-19 13:29:31 -04:00
|
|
|
@available = ::TimedQueue.new
|
|
|
|
@oid = @available.object_id
|
2011-05-14 15:29:51 -04:00
|
|
|
@options = DEFAULTS.merge(options)
|
|
|
|
@options[:size].times do
|
2011-09-19 13:29:31 -04:00
|
|
|
@available << block.call
|
2011-05-14 15:29:51 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def with(&block)
|
|
|
|
yield checkout
|
|
|
|
ensure
|
|
|
|
checkin
|
|
|
|
end
|
2011-05-14 22:42:07 -04:00
|
|
|
alias_method :with_connection, :with
|
2011-05-14 15:29:51 -04:00
|
|
|
|
|
|
|
def method_missing(name, *args)
|
|
|
|
checkout.send(name, *args)
|
|
|
|
ensure
|
|
|
|
checkin
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def checkout
|
2011-09-19 13:29:31 -04:00
|
|
|
::Thread.current[:"current-#{@oid}"] ||= begin
|
2011-09-18 15:05:52 -04:00
|
|
|
@available.timed_pop(@options[:timeout])
|
2011-05-14 15:29:51 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def checkin
|
2011-09-19 13:29:31 -04:00
|
|
|
conn = ::Thread.current[:"current-#{@oid}"]
|
|
|
|
::Thread.current[:"current-#{@oid}"] = nil
|
2011-09-09 17:12:23 -04:00
|
|
|
return unless conn
|
2011-05-14 15:29:51 -04:00
|
|
|
@available << conn
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
|
2011-09-09 17:12:23 -04:00
|
|
|
end
|