Verbindungspool mit einem benannten Connector erstellen

Erstellen Sie einen HikariCP-Verbindungspool, der eine Verbindung zu einer Datenbank über einen vorkonfigurierten benannten Connector herstellt. So können Sie bestimmte Konfigurationen wie eine Lazy-Refresh-Strategie für Anmeldedaten auf einen bestimmten Verbindungspool anwenden.

Codebeispiel

Java

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei AlloyDB zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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);
  }
}

Nächste Schritte

Wenn Sie nach Codebeispielen für andere Produkte von Google Cloud suchen und filtern möchten, können Sie den Beispielbrowser fürGoogle Cloud verwenden.