Added connection validation to MySQL

This commit is contained in:
Rsl1122 2018-08-06 11:54:12 +03:00
parent cccdf14e9b
commit 8641bd5f0d

View File

@ -1,6 +1,7 @@
package com.djrapitops.plan.system.database.databases.sql; package com.djrapitops.plan.system.database.databases.sql;
import com.djrapitops.plan.api.exceptions.database.DBInitException; import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.system.locale.Locale; import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang; import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.Settings; import com.djrapitops.plan.system.settings.Settings;
@ -33,6 +34,7 @@ public class MySQLDB extends SQLDB {
*/ */
@Override @Override
public void setupDataSource() throws DBInitException { public void setupDataSource() throws DBInitException {
try {
HikariConfig config = new HikariConfig(); HikariConfig config = new HikariConfig();
String host = Settings.DB_HOST.toString(); String host = Settings.DB_HOST.toString();
@ -56,11 +58,15 @@ public class MySQLDB extends SQLDB {
increment++; increment++;
config.setAutoCommit(true); config.setAutoCommit(true);
config.setReadOnly(false);
config.setMaximumPoolSize(8); config.setMaximumPoolSize(8);
config.setLeakDetectionThreshold(TimeAmount.MINUTE.ms() * 10L); config.setLeakDetectionThreshold(TimeAmount.MINUTE.ms() * 10L);
this.dataSource = new HikariDataSource(config); this.dataSource = new HikariDataSource(config);
getConnection();
} catch (SQLException e) {
throw new DBInitException("Failed to set-up HikariCP Datasource: " + e.getMessage(), e);
}
} }
/** /**
@ -73,7 +79,18 @@ public class MySQLDB extends SQLDB {
@Override @Override
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
return dataSource.getConnection(); Connection connection = dataSource.getConnection();
if (!connection.isValid(5)) {
if (dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).close();
}
try {
setupDataSource();
} catch (DBInitException e) {
throw new DBOpException("Failed to restart DataSource after a connection was invalid: " + e.getMessage(), e);
}
}
return connection;
} }
@Override @Override