Class: ConnectionPool

Inherits:
Object
  • Object
show all
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

Using optional timeout override (for that single invocation)

@pool.with(:timeout => 2.0) 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: Error, PoolShuttingDownError, TimedStack, Wrapper

Constant Summary collapse

DEFAULTS =
{size: 5, timeout: 5}
VERSION =
"2.0.0"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ ConnectionPool

Returns a new instance of ConnectionPool.

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
50
51
52
53
# File 'lib/connection_pool.rb', line 43

def initialize(options = {}, &block)
  raise ArgumentError, 'Connection pool requires a block' unless block

  options = DEFAULTS.merge(options)

  @size = options.fetch(:size)
  @timeout = options.fetch(:timeout)

  @available = TimedStack.new(@size, &block)
  @key = :"current-#{@available.object_id}"
end

Class Method Details

.wrap(options, &block) ⇒ Object



39
40
41
# File 'lib/connection_pool.rb', line 39

def self.wrap(options, &block)
  Wrapper.new(options, &block)
end

Instance Method Details

#checkinObject



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/connection_pool.rb', line 78

def checkin
  stack = ::Thread.current[@key]
  raise ConnectionPool::Error, 'no connections are checked out' if
    !stack || stack.empty?

  conn = stack.pop
  if stack.empty?
    @available << conn
  end
  nil
end

#checkout(options = {}) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/connection_pool.rb', line 64

def checkout(options = {})
  stack = ::Thread.current[@key] ||= []

  if stack.empty?
    timeout = options[:timeout] || @timeout
    conn = @available.pop(timeout)
  else
    conn = stack.last
  end

  stack.push conn
  conn
end

#shutdown(&block) ⇒ Object



90
91
92
# File 'lib/connection_pool.rb', line 90

def shutdown(&block)
  @available.shutdown(&block)
end

#with(options = {}) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/connection_pool.rb', line 55

def with(options = {})
  conn = checkout(options)
  begin
    yield conn
  ensure
    checkin
  end
end