Skip to content

Instantly share code, notes, and snippets.

@behitek
Created March 30, 2021 13:15
Show Gist options
  • Save behitek/32d0b1059e305bde08a529a20028c9e2 to your computer and use it in GitHub Desktop.
Save behitek/32d0b1059e305bde08a529a20028c9e2 to your computer and use it in GitHub Desktop.
package utils;
import org.apache.commons.dbcp2.*;
import org.apache.commons.pool2.impl.GenericObjectPool;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class SQLConnectionPool {
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String connectionUrl = "jdbc:mysql://" +
Configuration.getInstance().getConfig("MYSQL_HOST") + ":" +
Configuration.getInstance().getConfig("MYSQL_PORT") + "/" +
Configuration.getInstance().getConfig("MYSQL_DB") +
"?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&interactiveClient=true&useSSL=false";
private DataSource dataSource;
public SQLConnectionPool() {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//
// First, we'll create a ConnectionFactory that the
// pool will use to create Connections.
// We'll use the DriverManagerConnectionFactory,
// using the connect string passed in the command line
// arguments.
//
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectionUrl,
Configuration.getInstance().getConfig("MYSQL_USER"),
Configuration.getInstance().getConfig("MYSQL_PASS"));
//
// Next we'll create the PoolableConnectionFactory, which wraps
// the "real" Connections created by the ConnectionFactory with
// the classes that implement the pooling functionality.
//
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
connectionFactory,
null
);
//
// Now we'll need a ObjectPool that serves as the
// actual pool of connections.
//
// We'll use a GenericObjectPool instance, although
// any ObjectPool implementation will suffice.
//
GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
// Set the factory's pool property to the owning pool
poolableConnectionFactory.setPool(connectionPool);
//
// Finally, we create the PoolingDriver itself,
// passing in the object pool we created.
//
this.dataSource = new PoolingDataSource<>(connectionPool);
}
public Connection getConnection() throws SQLException {
//
// Get connection from pool
// When done, use Connection.close() to return it to pool
//
return this.dataSource.getConnection();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment