Menghubungkan menggunakan AlloyDB Language Connectors

Untuk menyederhanakan pembuatan koneksi yang aman dari aplikasi Anda ke cluster AlloyDB untuk PostgreSQL, Anda dapat menggunakan Konektor Bahasa AlloyDB. Library klien ini menyediakan kemampuan berikut:

  • Koneksi mTLS otomatis
  • Dukungan otorisasi berbasis Identity and Access Management (IAM)
  • Autentikasi IAM otomatis

Konektor Bahasa AlloyDB tidak dapat menyediakan jalur jaringan ke cluster AlloyDB jika jalur jaringan belum ada.

Untuk mengetahui informasi selengkapnya tentang Konektor Bahasa AlloyDB, lihat Ringkasan Konektor Bahasa AlloyDB.

Halaman ini membahas Konektor Bahasa AlloyDB berikut:

  • Konektor Java AlloyDB
  • Konektor Go AlloyDB
  • Konektor Python AlloyDB

Sebelum memulai

  1. Mengaktifkan AlloyDB API.

    Mengaktifkan API

  2. Membuat instance AlloyDB dan mengonfigurasi pengguna default.

    Untuk mengetahui informasi selengkapnya tentang cara membuat instance, lihat Membuat instance utama.

    Untuk mengetahui informasi selengkapnya tentang peran pengguna, lihat Peran IAM AlloyDB yang telah ditetapkan.

  3. Konfigurasikan peran IAM berikut yang diperlukan untuk terhubung ke instance AlloyDB:

    • AlloyDB Client (roles/alloydb.client)
    • Service Usage Consumer (roles/serviceusage.serviceUsageConsumer)

      Untuk mengetahui informasi selengkapnya tentang peran dan izin yang diperlukan, lihat Mengelola autentikasi IAM.

Menginstal Konektor Bahasa AlloyDB

Java

Konektor Java AlloyDB adalah library yang memberikan otorisasi dan enkripsi berbasis IAM saat terhubung ke instance AlloyDB. Jika Anda menggunakan Spring Boot, lihat Spring Boot AlloyDB starter.

Penginstalan

Untuk Maven, Anda dapat menginstal Konektor Java AlloyDB dengan menambahkan kode berikut ke pom.xml project Anda:

<!-- Add the connector with the latest version -->
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>alloydb-jdbc-connector</artifactId>
  <version>1.12.1</version>
</dependency>

<!-- Add the driver with the latest version -->
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.7.5</version>
</dependency>

<!-- Add HikariCP with the latest version -->
<dependency>
  <groupId>com.zaxxer</groupId>
  <artifactId>HikariCP</artifactId>
  <version>5.1.0</version>
</dependency>

Untuk Gradle, Anda dapat menginstal Konektor Java AlloyDB dengan menyertakan kode berikut dalam build.gradle project Anda:

// Add connector with the latest version
implementation group: 'com.google.cloud.alloydb', name: 'alloydb-jdbc-connector', version: '1.12.1'

// Add driver with the latest version
implementation group: 'org.postgresql', name: 'postgresql', version: '42.7.5'

// Add HikariCP with the latest version
implementation group: 'com.zaxxer', name: 'HikariCP', version: '5.1.0'

Python (pg8000)

Konektor Python AlloyDB berfungsi dengan driver database pg8000 (sinkron) dan asyncpg (asinkron) untuk memungkinkan akun utama dengan izin yang memadai terhubung ke database AlloyDB tanpa memasukkan alamat IP ke daftar yang diizinkan secara manual.

Penginstalan

Anda dapat menginstal library AlloyDB Python Connector dengan pip install.

Jika Anda menggunakan pg8000, jalankan perintah berikut:

pip install "google-cloud-alloydb-connector[pg8000]" sqlalchemy

Python (asyncpg)

Konektor Python AlloyDB berfungsi dengan driver database pg8000 (sinkron) dan asyncpg (asinkron) untuk memungkinkan akun utama dengan izin yang memadai terhubung ke database AlloyDB tanpa memasukkan alamat IP ke daftar yang diizinkan secara manual.

Penginstalan

Anda dapat menginstal library AlloyDB Python Connector dengan pip install.

Jika Anda menggunakan asyncpg, jalankan perintah berikut:

pip install "google-cloud-alloydb-connector[asyncpg]" "sqlalchemy[asyncio]"

Untuk mengetahui informasi selengkapnya tentang penggunaan driver asinkron, lihat Penggunaan Driver Asinkron.

Go (pgx)

Konektor Go AlloyDB adalah konektor AlloyDB yang dirancang untuk digunakan dengan bahasa Go.

Penginstalan

Anda dapat menginstal AlloyDB Go Connector dengan go get.

Jika Anda menggunakan pgx, jalankan perintah berikut:

go get github.com/jackc/pgx/v5
go get cloud.google.com/go/alloydbconn

Go (database/sql)

Konektor Go AlloyDB adalah konektor AlloyDB yang dirancang untuk digunakan dengan bahasa Go.

Penginstalan

Anda dapat menginstal AlloyDB Go Connector dengan go get.

Jika Anda menggunakan database/sql, jalankan perintah berikut:

go get cloud.google.com/go/alloydbconn

Mengonfigurasi Konektor Bahasa AlloyDB

Java

Untuk menggunakan Konektor AlloyDB Java agar terhubung ke cluster AlloyDB, konfigurasikan menggunakan langkah-langkah berikut.

Untuk menggunakan cuplikan ini dalam konteks aplikasi web, lihat README di GitHub.


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

public class AlloyDbJdbcConnectorDataSourceFactory {

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

  static HikariDataSource createDataSource() {
    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);

    return new HikariDataSource(config);
  }
}

Menggunakan IP publik

Jika Anda menggunakan IP publik untuk terhubung ke cluster AlloyDB, sertakan hal berikut:

config.addDataSourceProperty("alloydbIpType", "PUBLIC");

Menggunakan Private Service Connect

Jika Anda menggunakan Private Service Connect untuk terhubung ke instance AlloyDB, sertakan hal berikut:

config.addDataSourceProperty("alloydbIpType", "PSC");

Autentikasi IAM otomatis

Secara default, Konektor Bahasa AlloyDB menggunakan autentikasi bawaan. Anda dapat menggunakan autentikasi IAM otomatis dengan Konektor Java AlloyDB. Untuk mengaktifkannya, sertakan hal berikut:

config.addDataSourceProperty("alloydbEnableIAMAuth", "true");

Python (pg8000)

Untuk menggunakan Konektor Python AlloyDB guna terhubung ke cluster AlloyDB, konfigurasikan konektor menggunakan langkah-langkah berikut, jika Anda menggunakan pg8000.

Untuk menggunakan cuplikan ini dalam konteks aplikasi web, lihat README di GitHub.

import sqlalchemy

from google.cloud.alloydbconnector import Connector


def create_sqlalchemy_engine(
    inst_uri: str,
    user: str,
    password: str,
    db: str,
    refresh_strategy: str = "background",
) -> tuple[sqlalchemy.engine.Engine, Connector]:
    """Creates a connection pool for an AlloyDB instance and returns the pool
    and the connector. Callers are responsible for closing the pool and the
    connector.

    A sample invocation looks like:

        engine, connector = create_sqlalchemy_engine(
            inst_uri,
            user,
            password,
            db,
        )
        with engine.connect() as conn:
            time = conn.execute(sqlalchemy.text("SELECT NOW()")).fetchone()
            conn.commit()
            curr_time = time[0]
            # do something with query result
            connector.close()

    Args:
        instance_uri (str):
            The instance URI specifies the instance relative to the project,
            region, and cluster. For example:
            "projects/my-project/locations/us-central1/clusters/my-cluster/instances/my-instance"
        user (str):
            The database user name, e.g., postgres
        password (str):
            The database user's password, e.g., secret-password
        db (str):
            The name of the database, e.g., mydb
        refresh_strategy (Optional[str]):
            Refresh strategy for the AlloyDB Connector. Can be one of "lazy"
            or "background". For serverless environments use "lazy" to avoid
            errors resulting from CPU being throttled.
    """
    connector = Connector(refresh_strategy=refresh_strategy)

    # create SQLAlchemy connection pool
    engine = sqlalchemy.create_engine(
        "postgresql+pg8000://",
        creator=lambda: connector.connect(
            inst_uri,
            "pg8000",
            user=user,
            password=password,
            db=db,
        ),
    )
    engine.dialect.description_encoding = None
    return engine, connector

Menggunakan IP publik

Jika Anda menggunakan IP publik untuk terhubung ke cluster AlloyDB, ganti fungsi koneksi Anda dengan kode berikut:

  def getconn() -> pg8000.dbapi.Connection:
      conn: pg8000.dbapi.Connection = connector.connect(
          inst_uri,
          "pg8000",
          user=user,
          password=password,
          db=db,
          # use ip_type to specify public IP
          ip_type=IPTypes.PUBLIC,
      )
      return conn

Menggunakan Private Service Connect

Jika Anda menggunakan Private Service Connect untuk terhubung ke instance AlloyDB, sertakan hal berikut:

  def getconn() -> pg8000.dbapi.Connection:
      conn: pg8000.dbapi.Connection = connector.connect(
          inst_uri,
          "pg8000",
          user=user,
          password=password,
          db=db,
          # use ip_type to specify PSC
          ip_type=IPTypes.PSC,
        )
      return conn

Autentikasi IAM otomatis

Secara default, Konektor Bahasa AlloyDB menggunakan autentikasi bawaan. Anda dapat menggunakan autentikasi IAM otomatis dengan Konektor Python AlloyDB. Untuk mengaktifkannya, ganti fungsi koneksi Anda dengan kode berikut:

  def getconn() -> pg8000.dbapi.Connection:
      conn: pg8000.dbapi.Connection = connector.connect(
          inst_uri,
          "pg8000",
          user=user,
          password=password,
          db=db,
          # use enable_iam_auth to enable IAM authentication
          enable_iam_auth=True,
      )
      return conn

Python (asyncpg)

Untuk menggunakan Konektor Python AlloyDB guna terhubung ke cluster AlloyDB, konfigurasikan konektor menggunakan langkah-langkah berikut, jika Anda menggunakan asyncpg.

Untuk menggunakan cuplikan ini dalam konteks aplikasi web, lihat README di GitHub.

import asyncpg
import sqlalchemy
import sqlalchemy.ext.asyncio

from google.cloud.alloydbconnector import AsyncConnector


async def create_sqlalchemy_engine(
    inst_uri: str,
    user: str,
    password: str,
    db: str,
    refresh_strategy: str = "background",
) -> tuple[sqlalchemy.ext.asyncio.engine.AsyncEngine, AsyncConnector]:
    """Creates a connection pool for an AlloyDB instance and returns the pool
    and the connector. Callers are responsible for closing the pool and the
    connector.

    A sample invocation looks like:

        engine, connector = await create_sqlalchemy_engine(
            inst_uri,
            user,
            password,
            db,
        )
        async with engine.connect() as conn:
            time = await conn.execute(sqlalchemy.text("SELECT NOW()")).fetchone()
            curr_time = time[0]
            # do something with query result
            await connector.close()

    Args:
        instance_uri (str):
            The instance URI specifies the instance relative to the project,
            region, and cluster. For example:
            "projects/my-project/locations/us-central1/clusters/my-cluster/instances/my-instance"
        user (str):
            The database user name, e.g., postgres
        password (str):
            The database user's password, e.g., secret-password
        db (str):
            The name of the database, e.g., mydb
        refresh_strategy (Optional[str]):
            Refresh strategy for the AlloyDB Connector. Can be one of "lazy"
            or "background". For serverless environments use "lazy" to avoid
            errors resulting from CPU being throttled.
    """
    connector = AsyncConnector(refresh_strategy=refresh_strategy)

    # create SQLAlchemy connection pool
    engine = sqlalchemy.ext.asyncio.create_async_engine(
        "postgresql+asyncpg://",
        async_creator=lambda: connector.connect(
            inst_uri,
            "asyncpg",
            user=user,
            password=password,
            db=db,
        ),
        execution_options={"isolation_level": "AUTOCOMMIT"},
    )
    return engine, connector

Menggunakan IP publik

Jika Anda menggunakan IP publik untuk terhubung ke cluster AlloyDB, ganti fungsi koneksi Anda dengan kode berikut:

  async def getconn() -> asyncpg.Connection:
    conn: asyncpg.Connection = await connector.connect(
        inst_uri,
        "asyncpg",
        user=user,
        password=password,
        db=db,
        # use ip_type to specify public IP
        ip_type=IPTypes.PUBLIC,
    )
    return conn

Menggunakan Private Service Connect

Jika Anda menggunakan Private Service Connect untuk terhubung ke instance AlloyDB, sertakan hal berikut:

    async def getconn() -> asyncpg.Connection:
      conn: asyncpg.Connection = await connector.connect(
          inst_uri,
          "asyncpg",
          user=user,
          password=password,
          db=db,
          # use ip_type to specify PSC
          ip_type=IPTypes.PSC,
      )
      return conn

Autentikasi IAM otomatis

Secara default, Konektor Bahasa AlloyDB menggunakan autentikasi bawaan. Anda dapat menggunakan autentikasi IAM otomatis dengan Konektor Python AlloyDB. Untuk mengaktifkannya, ganti fungsi koneksi Anda dengan kode berikut:

  async def getconn() -> asyncpg.Connection:
    conn: asyncpg.Connection = await connector.connect(
        inst_uri,
        "asyncpg",
        user=user,
        password=password,
        db=db,
        # use enable_iam_auth to enable IAM authentication
        enable_iam_auth=True,
    )
    return conn

Go (pgx)

Untuk menggunakan AlloyDB Go Connector guna terhubung ke cluster AlloyDB, konfigurasikan konektor menggunakan langkah-langkah berikut, jika Anda menggunakan pgx.

Untuk menggunakan cuplikan ini dalam konteks aplikasi web, lihat README di GitHub.

import (
	"context"
	"fmt"
	"net"

	"cloud.google.com/go/alloydbconn"
	"github.com/jackc/pgx/v5/pgxpool"
)

// connectPgx establishes a connection to your database using pgxpool and the
// AlloyDB Go Connector (aka alloydbconn.Dialer)
//
// The function takes an instance URI, a username, a password, and a database
// name. Usage looks like this:
//
//	pool, cleanup, err := connectPgx(
//	  context.Background(),
//	  "projects/myproject/locations/us-central1/clusters/mycluster/instances/myinstance",
//	  "postgres",
//	  "secretpassword",
//	  "mydb",
//	)
//
// In addition to a *pgxpool.Pool type, the function returns a cleanup function
// that should be called when you're done with the database connection.
func connectPgx(
	ctx context.Context, instURI, user, pass, dbname string,
	opts ...alloydbconn.Option,
) (*pgxpool.Pool, func() error, error) {
	// First initialize the dialer. alloydbconn.NewDialer accepts additional
	// options to configure credentials, timeouts, etc.
	//
	// For details, see:
	// https://pkg.go.dev/cloud.google.com/go/alloydbconn#Option
	d, err := alloydbconn.NewDialer(ctx, opts...)
	if err != nil {
		noop := func() error { return nil }
		return nil, noop, fmt.Errorf("failed to init Dialer: %v", err)
	}
	// The cleanup function will stop the dialer's background refresh
	// goroutines. Call it when you're done with your database connection to
	// avoid a goroutine leak.
	cleanup := func() error { return d.Close() }

	dsn := fmt.Sprintf(
		// sslmode is disabled, because the Dialer will handle the SSL
		// connection instead.
		"user=%s password=%s dbname=%s sslmode=disable",
		user, pass, dbname,
	)

	// Prefer pgxpool for applications.
	// For more information, see:
	// https://github.com/jackc/pgx/wiki/Getting-started-with-pgx#using-a-connection-pool
	config, err := pgxpool.ParseConfig(dsn)
	if err != nil {
		return nil, cleanup, fmt.Errorf("failed to parse pgx config: %v", err)
	}

	// Tell pgx to use alloydbconn.Dialer to connect to the instance.
	config.ConnConfig.DialFunc = func(ctx context.Context, _ string, _ string) (net.Conn, error) {
		return d.Dial(ctx, instURI)
	}

	// Establish the connection.
	pool, connErr := pgxpool.NewWithConfig(ctx, config)
	if connErr != nil {
		return nil, cleanup, fmt.Errorf("failed to connect: %s", connErr)
	}

	return pool, cleanup, nil
}

Menggunakan IP publik

Jika Anda menggunakan IP publik untuk terhubung ke cluster AlloyDB, ganti fungsi d.Dial dengan kode berikut:

d.Dial(ctx, instURI, alloydbconn.WithPublicIP())

Menggunakan Private Service Connect

Jika Anda menggunakan Private Service Connect untuk terhubung ke instance AlloyDB, sertakan hal berikut:

  d.Dial(ctx, instURI, alloydbconn.WithPSC())

Autentikasi IAM otomatis

Secara default, Konektor Bahasa AlloyDB menggunakan autentikasi bawaan. Anda dapat menggunakan autentikasi IAM otomatis dengan Konektor Go AlloyDB. Untuk mengaktifkannya, ganti fungsi alloydbconn.NewDialer dengan kode berikut:

d, err := alloydbconn.NewDialer(ctx, alloydbconn.WithIAMAuthN())

Menonaktifkan telemetri bawaan

Opsi WithOptOutOfBuiltInTelemetry menonaktifkan ekspor metrik internal. Secara default, Dialer melaporkan operasi internalnya ke awalan metrik sistem alloydb.googleapis.com. Metrik ini membantu AlloyDB meningkatkan performa dan mengidentifikasi masalah konektivitas klien. Opsi ini berguna untuk aplikasi yang beroperasi di lingkungan tempat ekspor metrik keluar dibatasi. Untuk menonaktifkan telemetri ini, berikan opsi berikut saat melakukan inisialisasi Dialer:

  d.Dial(ctx, instURI, alloydbconn.WithOptOutOfBuiltInTelemetry())

Go (database/sql)

Untuk menggunakan AlloyDB Go Connector guna terhubung ke cluster AlloyDB, konfigurasikan konektor menggunakan langkah-langkah berikut, jika Anda menggunakan database/sql.

Untuk menggunakan cuplikan ini dalam konteks aplikasi web, lihat README di GitHub.

import (
	"database/sql"
	"fmt"

	"cloud.google.com/go/alloydbconn"
	"cloud.google.com/go/alloydbconn/driver/postgres"
)

// connectDatabaseSQL establishes a connection to your database using the Go
// standard library's database/sql package and using the AlloyDB Go Connector
// (aka alloydbconn.Dialer)
//
// The function takes an instance URI, a username, a password, and a database
// name. Usage looks like this:
//
//	db, cleanup, err := connectDatabaseSQL(
//	  "projects/myproject/locations/us-central1/clusters/mycluster/instances/myinstance",
//	  "postgres",
//	  "secretpassword",
//	  "mydb",
//	)
//
// In addition to a *db.SQL type, the function returns a cleanup function that
// should be called when you're done with the database connection.
func connectDatabaseSQL(
	instURI, user, pass, dbname string,
	opts ...alloydbconn.Option,
) (*sql.DB, func() error, error) {
	// First, register the AlloyDB driver. Note, the driver's name is arbitrary
	// and must only match what you use below in sql.Open. Also,
	// postgres.RegisterDriver accepts options to configure credentials, timeouts,
	// etc.
	//
	// For details, see:
	// https://pkg.go.dev/cloud.google.com/go/alloydbconn#Option
	//
	// The cleanup function will stop the dialer's background refresh
	// goroutines. Call it when you're done with your database connection to
	// avoid a goroutine leak.
	cleanup, err := postgres.RegisterDriver("alloydb", opts...)
	if err != nil {
		return nil, cleanup, err
	}

	db, err := sql.Open(
		"alloydb",
		fmt.Sprintf(
			// sslmode is disabled, because the Dialer will handle the SSL
			// connection instead.
			"host=%s user=%s password=%s dbname=%s sslmode=disable",
			instURI, user, pass, dbname,
		),
	)
	return db, cleanup, err
}

Menggunakan IP publik

Jika Anda menggunakan IP publik untuk terhubung ke cluster AlloyDB, ganti fungsi RegisterDriver dengan kode berikut:

cleanup, err := postgres.RegisterDriver(
  "alloydb",
  alloydbconn.WithDefaultDialOptions(alloydbconn.WithPublicIP()),
)

Menggunakan Private Service Connect

Jika Anda menggunakan Private Service Connect untuk terhubung ke instance AlloyDB, sertakan hal berikut:

cleanup, err := postgres.RegisterDriver(
  "alloydb",
  alloydbconn.WithDefaultDialOptions(alloydbconn.WithPSC()),
)

Autentikasi IAM otomatis

Secara default, Konektor Bahasa AlloyDB menggunakan autentikasi bawaan. Anda dapat menggunakan autentikasi IAM otomatis dengan Konektor Go AlloyDB. Untuk mengaktifkannya, ganti fungsi RegisterDriver Anda dengan kode berikut:

cleanup, err := postgres.RegisterDriver(
  "alloydb",
  alloydbconn.WithIAMAuthN(),
)

Menonaktifkan telemetri bawaan

Opsi WithOptOutOfBuiltInTelemetry menonaktifkan ekspor metrik internal. Secara default, Dialer melaporkan operasi internalnya ke awalan metrik sistem alloydb.googleapis.com. Metrik ini membantu AlloyDB meningkatkan performa dan mengidentifikasi masalah konektivitas klien. Opsi ini berguna untuk aplikasi yang beroperasi di lingkungan tempat ekspor metrik keluar dibatasi. Untuk menonaktifkan telemetri ini, berikan opsi berikut saat melakukan inisialisasi Dialer:

cleanup, err := postgres.RegisterDriver(
  "alloydb",
  alloydbconn.WithOptOutOfBuiltInTelemetry(),
)