Connection pool
Since databases are separate services from the application using them, the connections might go down, the services might be restarted, and other sort of things the program might not want to care about.
To address this issues usually a connection pool is a neat solution.
When a database is opened with there is already a connection pool working. DB.open
returns a DB::Database
object which manages the whole connection pool and not just a single connection.
- Checkout that connection from the pool.
- Execute the SQL command.
- Return the statement result.
If a connection can’t be created, or if a connection loss occurs while the statement is performed the above process is repeated.
The behavior of the pool can be configured from a set of parameters that can appear as query string in the connection URI.
If the max_pool_size
was reached and a connection is needed, wait up to checkout_timeout
seconds for an existing connection to become available.
If a connection is lost or can’t be established retry at most retry_attempts
times waiting retry_delay
seconds between each try.
Sample
The following program will print the current time from MySQL but if the connection is lost or the whole server is down for a few seconds the program will still run without raising exceptions.