Create a connection pool with IAM database authentication

This snippet shows how to configure a HikariCP connection pool to connect to an instance's private IP address. It uses a custom data source that automatically manages OAuth2 tokens to enable passwordless authentication with an IAM database user.

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 AlloyDbJdbcDirectPathDataSourceFactory {

  public static final String ALLOYDB_DB = System.getenv("ALLOYDB_DB");
  public static final String ALLOYDB_USER = System.getenv("ALLOYDB_IAM_USER");
  public static final String ALLOYDB_INSTANCE_IP = System.getenv("ALLOYDB_INSTANCE_IP");

  static HikariDataSource createDataSource() {
    HikariConfig config = new HikariConfig();

    config.setJdbcUrl(String.format("jdbc:postgresql://%s/%s", ALLOYDB_INSTANCE_IP, ALLOYDB_DB));
    config.setUsername(ALLOYDB_USER); // e.g., "postgres"
    // No need to set password, as that's dynamically configured in the
    // AlloyDBDirectPathDataSource with a refreshed OAuth2 token.

    return new AlloyDBDirectPathDataSource(config);
  }
}

What's next

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