Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class HikariCPFactory {
- private static final Logger LOGGER = LoggerFactory.getLogger(HikariCPFactory.class);
- @Override
- public DataSource apply(Config config) {
- LOGGER.debug("ConnectionPool initializing...");
- HikariConfig hc = new HikariConfig();
- // optional
- if (config.hasPath("jdbc.driver")) {
- hc.setDriverClassName(config.getString("jdbc.driver"));
- } else {
- hc.setDriverClassName("org.postgresql.Driver");
- }
- hc.setJdbcUrl(databaseUrl(config));
- hc.setUsername(config.getString("jdbc.username"));
- hc.setPassword(config.getString("jdbc.password"));
- // init cp specific properties
- hc.setInitializationFailFast(true);
- hc.setConnectionTestQuery("SELECT 1");
- if (config.hasPath("hikaricp")) {
- // enumerate all properties
- Config config0 = config.getConfig("hikaricp");
- Set<Map.Entry<String, ConfigValue>> set = config0.entrySet();
- for (Map.Entry<String, ConfigValue> entry : set) {
- hc.addDataSourceProperty(entry.getKey(), entry.getValue());
- }
- }
- LOGGER.debug("ConnectionPool initialized {}", hc);
- return new HikariDataSource(hc);
- }
- @SuppressWarnings("Duplicates")
- public static String databaseUrl(final Config config) {
- String protocol = config.getString("jdbc.protocol");
- String host = config.getString("jdbc.host");
- int port = config.getInt("jdbc.port");
- String database = config.getString("jdbc.database");
- return protocol + "//" + host + ":" + port + "/" + database;
- }
- }
- /// usage
- HikariCPFactory hcp = new HikariCPFactory();
- dsApple = hcp.apply(fallback(config, "apple"));
- dsSpotify = hcp.apply(fallback(config, "spotify"));
- /// where
- public static Config fallback(Config config, String namespace) {
- // we need to be able to get, for example, "spotify.jdbc.username"
- // when we have defined "jdbc.username" only
- return config.getConfig(namespace)
- .withFallback(config);
- }
- /// config
- jdbc {
- driver = org.postgresql.Driver
- protocol = "jdbc:postgresql:"
- host = localhost
- port = 5432
- username = "postgres"
- password = "postgres"
- database = my_db
- }
- spotify {
- jdbc.host = "cloud.us-west-2.rds.amazonaws.com"
- jdbc.database = spotify_db
- }
- apple {
- jdbc.host = "cloud.us-west-2.rds.amazonaws.com"
- jdbc.database = apple_db
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement