Class: Telegram::ConnectionPool

Inherits:
Array
  • Object
show all
Includes:
Logging
Defined in:
lib/telegram/connection_pool.rb

Overview

Connection Pool

See Also:

Version:

  • 0.1.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

configure_logger_for, #logger, logger_for

Constructor Details

#initialize(size = 10, &block) ⇒ ConnectionPool

Initialize ConnectionPool

Parameters:

  • size (Integer) (defaults to: 10)

    Connection pool size

  • block (Block)

    Create a connection in this block, have to pass a Telegram::Connection object



16
17
18
19
20
# File 'lib/telegram/connection_pool.rb', line 16

def initialize(size=10, &block)
  size.times do 
    self << block.call if block_given?
  end
end

Instance Attribute Details

#sizeInteger (readonly)

Returns Connection pool size, will be set when initialized.

Returns:

  • (Integer)

    Connection pool size, will be set when initialized



10
11
12
# File 'lib/telegram/connection_pool.rb', line 10

def size
  @size
end

Instance Method Details

#acquire(&callback) {|connection| ... } ⇒ Object

Acquire available connection

Parameters:

  • callback (Block)

    This block will be called when successfully acquired a connection

Yield Parameters:

See Also:



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

def acquire(&callback)
  acq = Proc.new {
    conn = self.find { |conn| conn.available? }
    if not conn.nil? and conn.connected?
      callback.call(conn)
    else
      logger.warn("Failed to acquire available connection, retry after 0.1 second")
      EM.add_timer(0.1, &acq)
    end
  }
  EM.add_timer(0, &acq)
end

#communicate(*messages, &block) ⇒ Object

Communicate with acquired connection

Parameters:

  • messages (Array<String>)

    Messages that will be sent

  • block (Block)

    Callback block that will be called when finished

See Also:



27
28
29
30
31
32
33
34
35
36
# File 'lib/telegram/connection_pool.rb', line 27

def communicate(*messages, &block)
  begin
    acquire do |conn|
      conn.communicate(*messages, &block)
    end
  rescue Exception => e
    logger.error("Error occurred during the communicating: #{e.inspect} #{e.backtrace}")
  end

end