I'm using postgres 9.1, org.apache.commons.dbcp.BasicDataSource
(for my connection pool) and Java 1.7. When I restart my postgres server, I get exceptions like org.postgresql.util.PSQLException: FATAL: terminating connection due to administrator command
.
How can I make it so the connections automatically re-connect to the restarted database?
Connecting to a Local Database Using psqlServer [localhost]: Database [postgres]: Port [5432]: Username [postgres]: Password for user postgres: If you simply press Enter without entering any variables, they will be filled in automatically with the default values. Although, you will have to enter a password anyway.
To be sure that PostgreSQL is running, you can also restart it with systemctl restart postgresql. If this does not fix the problem, the most likely cause of this error is that PostgreSQL is not configured to allow TCP/IP connections.
DBCP has a connection validation query option - validationQuery
, according to the docs. You can set it to something like SELECT 1;
and DBCP will run that before returning a connection to test it.
That said, your app really should handle this case. SQL queries can fail for all sorts of reasons and you should always do your queries in a retry loop with a time back-off and retry limit, plus some logic to decide what exceptions are recoverable on retry and which aren't (use the SQLState for that).
In particular, validation is subject to a race condition where you can have event orderings like:
or
... so it remains important for your app to have a proper retry loop and good transaction handling.
You can get the SQLState from the SQLException: SQLException.getSQLState
. The codes for PostgreSQL are in the PostgreSQL manual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With