Class: Tina4::ConnectionPool
- Inherits:
-
Object
- Object
- Tina4::ConnectionPool
- Defined in:
- lib/tina4/database.rb
Overview
Thread-safe connection pool with round-robin rotation. Connections are created lazily on first use.
Instance Attribute Summary collapse
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
-
#active_count ⇒ Object
Number of connections that have been created.
-
#checkin(_driver) ⇒ Object
Return a driver to the pool.
-
#checkout ⇒ Object
Get the next driver via round-robin.
-
#close_all ⇒ Object
Close all active connections.
-
#initialize(pool_size, driver_factory:, connection_string:, username: nil, password: nil) ⇒ ConnectionPool
constructor
A new instance of ConnectionPool.
Constructor Details
#initialize(pool_size, driver_factory:, connection_string:, username: nil, password: nil) ⇒ ConnectionPool
Returns a new instance of ConnectionPool.
12 13 14 15 16 17 18 19 20 21 |
# File 'lib/tina4/database.rb', line 12 def initialize(pool_size, driver_factory:, connection_string:, username: nil, password: nil) @pool_size = pool_size @driver_factory = driver_factory @connection_string = connection_string @username = username @password = password @drivers = Array.new(pool_size) # nil slots — lazy creation @index = 0 @mutex = Mutex.new end |
Instance Attribute Details
#size ⇒ Object (readonly)
Returns the value of attribute size.
10 11 12 |
# File 'lib/tina4/database.rb', line 10 def size @size end |
Instance Method Details
#active_count ⇒ Object
Number of connections that have been created.
57 58 59 60 61 |
# File 'lib/tina4/database.rb', line 57 def active_count @mutex.synchronize do @drivers.count { |d| !d.nil? } end end |
#checkin(_driver) ⇒ Object
Return a driver to the pool. Currently a no-op for round-robin.
40 41 42 |
# File 'lib/tina4/database.rb', line 40 def checkin(_driver) # no-op end |
#checkout ⇒ Object
Get the next driver via round-robin. Thread-safe.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/tina4/database.rb', line 24 def checkout @mutex.synchronize do idx = @index @index = (@index + 1) % @pool_size if @drivers[idx].nil? driver = @driver_factory.call driver.connect(@connection_string, username: @username, password: @password) @drivers[idx] = driver end @drivers[idx] end end |
#close_all ⇒ Object
Close all active connections.
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/tina4/database.rb', line 45 def close_all @mutex.synchronize do @drivers.each_with_index do |driver, i| if driver driver.close rescue nil @drivers[i] = nil end end end end |