Skip to content

Instantly share code, notes, and snippets.

@mvineetmenon
Last active June 30, 2021 04:40
Show Gist options
  • Save mvineetmenon/8e8b2e3dafddb4e15e1ca2c45cb4859a to your computer and use it in GitHub Desktop.
Save mvineetmenon/8e8b2e3dafddb4e15e1ca2c45cb4859a to your computer and use it in GitHub Desktop.
Apache DBCP2 with SSL client authentication
import java.sql.ResultSet;
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestDBCP {
private BasicDataSource connectionPool;
public void init() {
String dbUrl = "jdbc:postgresql://server_ip:5432/postgres";
connectionPool = new BasicDataSource();
connectionPool.setDriverClassName("org.postgresql.Driver");
connectionPool.setUrl(dbUrl);
connectionPool.setUsername("postgres");
connectionPool.setPassword("postgres");
connectionPool.setInitialSize(1);
connectionPool.addConnectionProperty("ssl", "true");
connectionPool.addConnectionProperty("sslmode", "verify-ca");
connectionPool.addConnectionProperty("sslcert", "postgres-client.crt");
connectionPool.addConnectionProperty("sslkey", "postgres-client.key.pk8");
connectionPool.addConnectionProperty("sslrootcert", "ca.crt");
try ( Connection conn = connectionPool.getConnection()) {
// Do your thing with conn object
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
public static void main(String[] args) {
new TestDBCP().init();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment