Class: Forem::ConnectionManager
- Inherits:
-
Object
- Object
- Forem::ConnectionManager
- Defined in:
- lib/forem/connection_manager.rb
Overview
Manages a pool of persistent Net::HTTP connections keyed by host and port.
ConnectionManager is used internally by APIRequestor to reuse keep-alive TCP connections across multiple requests to the same server, reducing connection-setup overhead.
Each APIRequestor instance owns exactly one ConnectionManager. Connections are lazily created on first use and kept open with a 30-second keep-alive timeout.
Instance Method Summary collapse
-
#clear ⇒ void
Close all open connections and remove them from the pool.
-
#connection_for(uri, open_timeout: 30, read_timeout: 80) ⇒ Net::HTTP
Return a Net::HTTP connection for the given URI, creating one if needed.
-
#initialize ⇒ ConnectionManager
constructor
Create a new, empty ConnectionManager with no active connections.
Constructor Details
#initialize ⇒ ConnectionManager
Create a new, empty ConnectionManager with no active connections.
23 24 25 |
# File 'lib/forem/connection_manager.rb', line 23 def initialize @connections = {} end |
Instance Method Details
#clear ⇒ void
This method returns an undefined value.
Close all open connections and remove them from the pool.
Gracefully handles connections that are already closed by swallowing any IOError raised during shutdown. After this call the manager is empty and new connections will be created on the next #connection_for call.
66 67 68 69 70 71 72 73 |
# File 'lib/forem/connection_manager.rb', line 66 def clear @connections.each_value do |conn| conn.finish if conn.started? rescue IOError # already closed end @connections.clear end |
#connection_for(uri, open_timeout: 30, read_timeout: 80) ⇒ Net::HTTP
Return a Net::HTTP connection for the given URI, creating one if needed.
Connections are keyed by "host:port" so the same object is reused for every request to the same server. SSL is enabled automatically when the URI scheme is "https".
43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/forem/connection_manager.rb', line 43 def connection_for(uri, open_timeout: 30, read_timeout: 80) key = "#{uri.host}:#{uri.port}" return @connections[key] if @connections[key] conn = Net::HTTP.new(uri.host, uri.port) conn.use_ssl = uri.scheme == "https" conn.open_timeout = open_timeout conn.read_timeout = read_timeout conn.keep_alive_timeout = 30 @connections[key] = conn end |