Create a connection pool using a named connector

Create a HikariCP connection pool that connects to a database using a pre-configured named connector. This allows you to apply specific configurations, such as a lazy refresh strategy for credentials, to a particular connection pool.

Code sample

Java

To authenticate to AlloyDB, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

public class AlloyDbJdbcNamedConnectorDataSourceFactory {

  public static final String ALLOYDB_DB = System.getenv("ALLOYDB_DB");
  public static final String ALLOYDB_USER = System.getenv("ALLOYDB_USER");
  public static final String ALLOYDB_PASS = System.getenv("ALLOYDB_PASS");
  public static final String ALLOYDB_INSTANCE_NAME = System.getenv("ALLOYDB_INSTANCE_NAME");
  public static final String ALLOYDB_IMPERSONATED_USER = System.getenv("ALLOYDB_IMPERSONATED_USER");

  static HikariDataSource createDataSource() {

    // Register a named Connector
    ConnectorConfig namedConnectorConfig =
        new ConnectorConfig.Builder().withRefreshStrategy(RefreshStrategy.LAZY).build();
    ConnectorRegistry.register("my-connector", namedConnectorConfig);

    HikariConfig config = new HikariConfig();

    config.setJdbcUrl(String.format("jdbc:postgresql:///%s", ALLOYDB_DB));
    config.setUsername(ALLOYDB_USER); // e.g., "postgres"
    config.setPassword(ALLOYDB_PASS); // e.g., "secret-password"
    config.addDataSourceProperty("socketFactory", "com.google.cloud.alloydb.SocketFactory");
    // e.g., "projects/my-project/locations/us-central1/clusters/my-cluster/instances/my-instance"
    config.addDataSourceProperty("alloydbInstanceName", ALLOYDB_INSTANCE_NAME);
    config.addDataSourceProperty("alloydbNamedConnector", "my-connector");

    return new HikariDataSource(config);
  }
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.