Clean up MySQLConnection code slightly.

This commit is contained in:
AppleDash 2017-01-20 00:51:07 -05:00
parent 9d71bb5a21
commit b0be08d5dc
2 changed files with 27 additions and 10 deletions

View File

@ -11,6 +11,8 @@ public class DatabaseCredentials {
private final String password;
private final String databaseName;
private final String tablePrefix;
private final int maxRetries;
private final int queryTimeout;
public DatabaseCredentials(String hostname, int port, String username, String password, String databaseName, String tablePrefix) {
this.hostname = hostname;
@ -19,6 +21,8 @@ public class DatabaseCredentials {
this.password = password;
this.databaseName = databaseName;
this.tablePrefix = tablePrefix;
maxRetries = 5;
queryTimeout = 5000;
}
public String getHostname() {
@ -48,4 +52,12 @@ public class DatabaseCredentials {
public String getTablePrefix() {
return tablePrefix;
}
public int getMaxRetries() {
return maxRetries;
}
public int getQueryTimeout() {
return queryTimeout;
}
}

View File

@ -42,7 +42,7 @@ public class MySQLConnection {
public PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setQueryTimeout(5000); // 5 second timeout
preparedStatement.setQueryTimeout(dbCredentials.getQueryTimeout()); // 5 second timeout
return preparedStatement;
}
@ -66,21 +66,26 @@ public class MySQLConnection {
});
}
// This is a big weird because it has to account for recursion...
private void doExecuteAsyncOperation(int levels, Consumer<Connection> callback) {
waitForSlot();
openTransactions.incrementAndGet();
if (levels == 1) {
waitForSlot();
openTransactions.incrementAndGet();
}
try (Connection conn = openConnection()) {
callback.accept(conn);
} catch (Exception e) {
if (levels < 5) {
LOGGER.severe("An internal SQL error has occured, trying up to " + (5 - levels) + " more times...");
e.printStackTrace();
levels++;
doExecuteAsyncOperation(levels, callback);
if (levels > dbCredentials.getMaxRetries()) {
throw new RuntimeException("This shouldn't happen (database error)", e);
}
throw new RuntimeException("This shouldn't happen (database error)", e);
LOGGER.severe("An internal SQL error has occured, trying up to " + (5 - levels) + " more times...");
e.printStackTrace();
levels++;
doExecuteAsyncOperation(levels, callback);
} finally {
openTransactions.decrementAndGet();
if (levels == 1) {
openTransactions.decrementAndGet();
}
}
}