You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.2 KiB
87 lines
2.2 KiB
package org.leolo.rail; |
|
|
|
|
|
import java.sql.Connection; |
|
import java.sql.ResultSet; |
|
import java.sql.SQLException; |
|
import java.sql.Statement; |
|
|
|
import javax.sql.XAConnection; |
|
|
|
import org.apache.logging.log4j.LogManager; |
|
import org.apache.logging.log4j.Logger; |
|
import org.mariadb.jdbc.MariaDbPoolDataSource; |
|
|
|
public class DatabaseManager { |
|
|
|
private static Logger log = LogManager.getLogger(DatabaseManager.class); |
|
|
|
private static DatabaseManager instance; |
|
|
|
private MariaDbPoolDataSource ds; |
|
|
|
public synchronized static DatabaseManager getInstance() { |
|
if(instance==null) { |
|
instance = new DatabaseManager(); |
|
} |
|
return instance; |
|
} |
|
|
|
private DatabaseManager() { |
|
ConfigurationManager cm = ConfigurationManager.getInstance(); |
|
if( |
|
!cm.containsKey("db.host")|| |
|
!cm.containsKey("db.user")|| |
|
!cm.containsKey("db.pwd")|| |
|
!cm.containsKey("db.name") |
|
) { |
|
log.fatal("Missing required property"); |
|
System.exit(1); |
|
} |
|
String url = "jdbc:mariadb://"+cm.getProperty("db.host")+ |
|
":"+cm.getProperty("db.port", "3306")+ |
|
"/"+cm.getProperty("db.name"); |
|
log.info("Connecting to DB {} as {}", url, cm.get("db.user")); |
|
try { |
|
ds = new MariaDbPoolDataSource(url); |
|
ds.setMinPoolSize(1); |
|
ds.setMaxPoolSize(Integer.parseInt(cm.getOrDefault("db.poolsize", "20").toString())); |
|
ds.setUser(cm.getProperty("db.user").toString()); |
|
ds.setPassword(cm.getProperty("db.pwd").toString()); |
|
} catch (SQLException e) { |
|
log.fatal("Cannot connect to DB",e); |
|
System.exit(-2); |
|
} |
|
} |
|
|
|
public boolean testPool() { |
|
try(Connection conn = ds.getConnection()){ |
|
try(Statement stmt = conn.createStatement()){ |
|
try (ResultSet rs = stmt.executeQuery("SELECT CONNECTION_ID()")){ |
|
if(rs.next()) { |
|
log.debug("Connection ID: {}", rs.getString(1)); |
|
} |
|
} |
|
} |
|
} catch (SQLException e) { |
|
log.warn("Exception when testing the connection., e"); |
|
return false; |
|
} |
|
return true; |
|
} |
|
|
|
public Connection getConnection() throws SQLException { |
|
Connection conn = ds.getConnection(); |
|
conn.setAutoCommit(false); |
|
return conn; |
|
} |
|
|
|
public XAConnection getXAConnection() throws SQLException { |
|
XAConnection conn = ds.getXAConnection(); |
|
return conn; |
|
} |
|
|
|
public void shutdown() { |
|
ds.close(); |
|
} |
|
}
|
|
|