Class: Green::ConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/green/connection_pool.rb

Defined Under Namespace

Classes: Proxy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of ConnectionPool.



17
18
19
20
21
22
23
24
25
26
# File 'lib/green/connection_pool.rb', line 17

def initialize(opts = {}, &block)
  @available = []   # pool of free connections
  @pending   = []   # pending reservations (FIFO)

  @disconnect_class = opts[:disconnect_class]
  @new_block = block
  opts[:size].times do
    @available.push(@new_block.call)
  end
end

Instance Attribute Details

#availableObject

Returns the value of attribute available.



15
16
17
# File 'lib/green/connection_pool.rb', line 15

def available
  @available
end

#disconnect_classObject

Returns the value of attribute disconnect_class.



15
16
17
# File 'lib/green/connection_pool.rb', line 15

def disconnect_class
  @disconnect_class
end

#new_blockObject

Returns the value of attribute new_block.



15
16
17
# File 'lib/green/connection_pool.rb', line 15

def new_block
  @new_block
end

#pendingObject

Returns the value of attribute pending.



15
16
17
# File 'lib/green/connection_pool.rb', line 15

def pending
  @pending
end

Instance Method Details

#acquireObject



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

def acquire
  g = Green.current
  if conn = @available.pop
    conn
  else
    @pending.push g
    Green.hub.wait { @pending.delete g }
    acquire
  end
end

#executeObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/green/connection_pool.rb', line 28

def execute
  begin
    conn = acquire
    yield conn
  rescue => e
    if @disconnect_class && e.is_a?(@disconnect_class)
      disconnected = true
      @available << @new_block.call
    else
      raise
    end
  ensure
    if disconnected
      try_next
    else
      release conn
      try_next
    end
  end
end

#proxyObject



49
50
51
# File 'lib/green/connection_pool.rb', line 49

def proxy
  @proxy ||= Proxy.new(self)
end

#release(conn) ⇒ Object



64
65
66
# File 'lib/green/connection_pool.rb', line 64

def release(conn)
  @available.push conn
end

#try_nextObject



68
69
70
71
72
# File 'lib/green/connection_pool.rb', line 68

def try_next
  if pending = @pending.shift
    Green.hub.callback { pending.switch }
  end
end