Skip to content

Commit

Permalink
set network timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
StrikeW committed Jun 13, 2024
1 parent 7c31cf9 commit 1fb723f
Showing 1 changed file with 12 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ public static Connection getConnection(String jdbcUrl) throws SQLException {
// https://jdbc.postgresql.org/documentation/use/
// https://dev.mysql.com/doc/connectors/en/connector-j-connp-props-networking.html#cj-conn-prop_tcpKeepAlive
props.setProperty("tcpKeepAlive", "true");

// default timeout in seconds
final int CONNECTION_TIMEOUT = 30;
final int SOCKET_TIMEOUT = 300;
boolean isPg = jdbcUrl.startsWith("jdbc:postgresql");

// postgres use seconds and mysql use milliseconds
int connectTimeout = isPg ? CONNECTION_TIMEOUT : CONNECTION_TIMEOUT * 1000;
int socketTimeout = isPg ? SOCKET_TIMEOUT: SOCKET_TIMEOUT * 1000;
props.setProperty("connectTimeout", String.valueOf(connectTimeout));
props.setProperty("socketTimeout", String.valueOf(socketTimeout));

var conn = DriverManager.getConnection(jdbcUrl, props);
// disable auto commit can improve performance
conn.setAutoCommit(false);
Expand Down

0 comments on commit 1fb723f

Please sign in to comment.