חיבור באמצעות AlloyDB Language Connectors

כדי לפשט את תהליך יצירת החיבורים המאובטחים מהאפליקציה לאשכול AlloyDB ל-PostgreSQL, אתם יכולים להשתמש במחברי השפות ל-AlloyDB. ספריות הלקוח האלה מספקות את היכולות הבאות:

  • חיבורי mTLS אוטומטיים
  • תמיכה בהרשאות שמבוססות על ניהול זהויות והרשאות גישה (IAM)
  • אימות אוטומטי ב-IAM

מחברי שפות ל-AlloyDB לא יכולים לספק נתיב רשת לאשכול AlloyDB אם אין כבר נתיב רשת.

מידע נוסף על מחברי שפות ל-AlloyDB זמין במאמר סקירה כללית על מחברי שפות ל-AlloyDB.

בדף הזה נדון במחברי השפות הבאים ל-AlloyDB:

  • מחבר Java ל-AlloyDB
  • מחבר Go ל-AlloyDB
  • מחבר Python ל-AlloyDB

לפני שמתחילים

  1. מפעילים את AlloyDB API.

    הפעלת ה-API

  2. יוצרים מכונה של AlloyDB ומגדירים את משתמש ברירת המחדל.

    מידע נוסף על יצירת מכונה זמין במאמר יצירת מכונה ראשית.

    מידע נוסף על תפקידי משתמשים זמין במאמר תפקידי IAM מוגדרים מראש ב-AlloyDB.

  3. מגדירים את תפקידי ה-IAM הבאים שנדרשים כדי להתחבר למכונה של AlloyDB:

    • לקוח AlloyDB‏ (roles/alloydb.client)
    • Service Usage Consumer (roles/serviceusage.serviceUsageConsumer)

      במאמר ניהול אימות ב-IAM מוסבר אילו תפקידים והרשאות נדרשים.

התקנת מחברי השפות ל-AlloyDB

Java

מחבר Java ל-AlloyDB הוא ספרייה שמספקת הרשאה והצפנה שמבוססות על IAM כשמתחברים למכונה של AlloyDB. אם אתם משתמשים ב-Spring Boot, קראו את המאמר Spring Boot AlloyDB starter.

התקנה

כדי להתקין את מחבר Java ל-AlloyDB ב-Maven, מוסיפים את הקוד הבא לקובץ pom.xml של הפרויקט:

<!-- 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>

כדי להתקין את מחבר Java ל-AlloyDB ב-Gradle, מוסיפים את הקוד הבא לקובץ build.gradle של הפרויקט:

// 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)

מחבר Python ל-AlloyDB פועל עם מנהלי ההתקנים של מסד הנתונים pg8000 (סינכרוני) ו-asyncpg (אסינכרוני), כדי לאפשר לחשבונות משתמשים עם הרשאות מתאימות להתחבר למסד נתונים של AlloyDB בלי להוסיף ידנית כתובות IP לרשימת ההיתרים.

התקנה

אפשר להתקין את ספריית AlloyDB Python Connector באמצעות pip install.

אם משתמשים ב-pg8000, מריצים את הפקודה הבאה:

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

Python (asyncpg)

מחבר Python ל-AlloyDB פועל עם מנהלי ההתקנים של מסד הנתונים pg8000 (סינכרוני) ו-asyncpg (אסינכרוני), כדי לאפשר לחשבונות משתמשים עם הרשאות מתאימות להתחבר למסד נתונים של AlloyDB בלי להוסיף ידנית כתובות IP לרשימת ההיתרים.

התקנה

אפשר להתקין את ספריית AlloyDB Python Connector באמצעות pip install.

אם משתמשים ב-asyncpg, מריצים את הפקודה הבאה:

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

מידע נוסף על השימוש בדרייבר אסינכרוני זמין במאמר שימוש בדרייבר אסינכרוני.

Go (pgx)

מחבר Go ל-AlloyDB הוא מחבר ל-AlloyDB שמיועד לשימוש בשפת Go.

התקנה

אפשר להתקין את AlloyDB Go Connector באמצעות go get.

אם משתמשים ב-pgx, מריצים את הפקודות הבאות:

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

‫Go (מסד נתונים/SQL)

מחבר Go ל-AlloyDB הוא מחבר ל-AlloyDB שמיועד לשימוש בשפת Go.

התקנה

אפשר להתקין את AlloyDB Go Connector באמצעות go get.

אם משתמשים ב-database/sql, מריצים את הפקודה הבאה:

go get cloud.google.com/go/alloydbconn

הגדרת מחברי השפות ל-AlloyDB

Java

כדי להשתמש במחבר Java ל-AlloyDB כדי להתחבר לאשכול AlloyDB, צריך להגדיר אותו לפי השלבים הבאים.

כדי להשתמש בקטע הקוד הזה בהקשר של אפליקציית אינטרנט, עיינו ב-README ב-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);
  }
}

שימוש בכתובת IP ציבורית

אם אתם משתמשים בכתובת IP ציבורית כדי להתחבר לאשכול AlloyDB, צריך לכלול את הפרטים הבאים:

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

שימוש ב-Private Service Connect

אם אתם משתמשים ב-Private Service Connect כדי להתחבר למכונה של AlloyDB, צריך לכלול את הפרטים הבאים:

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

אימות אוטומטי ב-IAM

כברירת מחדל, מחברי השפות ל-AlloyDB משתמשים באימות מובנה. אתם יכולים להשתמש באימות אוטומטי ב-IAM עם מחבר Java ל-AlloyDB. כדי להפעיל את האפשרות הזו, צריך לכלול את הפרטים הבאים:

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

‫Python‏ (pg8000)

כדי להשתמש ב-AlloyDB Python Connector כדי להתחבר לאשכול AlloyDB, מגדירים את המחבר באמצעות השלבים הבאים, אם משתמשים ב-pg8000.

כדי להשתמש בקטע הקוד הזה בהקשר של אפליקציית אינטרנט, עיינו ב-README ב-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",
    ip_type: str = "PRIVATE",
) -> 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.
        ip_type (str):
            IP type used to connect. One of "PUBLIC", "PRIVATE" or "PSC".
    """
    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,
            ip_type=ip_type,
        ),
    )
    engine.dialect.description_encoding = None
    return engine, connector

שימוש בכתובת IP ציבורית

אם אתם משתמשים בכתובת IP ציבורית כדי להתחבר לאשכול AlloyDB, החליפו את פונקציית החיבור בקוד הבא:

  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

שימוש ב-Private Service Connect

אם אתם משתמשים ב-Private Service Connect כדי להתחבר למכונה של AlloyDB, צריך לכלול את הפרטים הבאים:

  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

אימות אוטומטי ב-IAM

כברירת מחדל, מחברי השפות ל-AlloyDB משתמשים באימות מובנה. אפשר להשתמש באימות אוטומטי ב-IAM עם AlloyDB Python Connector. כדי להפעיל אותו, מחליפים את פונקציית החיבור בקוד הבא:

  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)

כדי להשתמש ב-AlloyDB Python Connector כדי להתחבר לאשכול AlloyDB, מגדירים את המחבר באמצעות השלבים הבאים, אם משתמשים ב-asyncpg.

כדי להשתמש בקטע הקוד הזה בהקשר של אפליקציית אינטרנט, עיינו ב-README ב-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",
    ip_type: str = "PRIVATE",
) -> 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.
        ip_type (str):
            IP type used to connect. One of "PUBLIC", "PRIVATE" or "PSC".
    """
    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,
            ip_type=ip_type,
        ),
        execution_options={"isolation_level": "AUTOCOMMIT"},
    )
    return engine, connector

שימוש בכתובת IP ציבורית

אם אתם משתמשים בכתובת IP ציבורית כדי להתחבר לאשכול AlloyDB, החליפו את פונקציית החיבור בקוד הבא:

  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

שימוש ב-Private Service Connect

אם אתם משתמשים ב-Private Service Connect כדי להתחבר למכונה של AlloyDB, צריך לכלול את הפרטים הבאים:

    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

אימות אוטומטי ב-IAM

כברירת מחדל, מחברי השפות ל-AlloyDB משתמשים באימות מובנה. אפשר להשתמש באימות אוטומטי ב-IAM עם מחבר Python של AlloyDB. כדי להפעיל את זה, צריך להחליף את פונקציית החיבור בקוד הבא:

  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)

כדי להשתמש ב-AlloyDB Go Connector כדי להתחבר לאשכול AlloyDB, צריך להגדיר את המחבר באמצעות השלבים הבאים, אם משתמשים ב-pgx.

כדי להשתמש בקטע הקוד הזה בהקשר של אפליקציית אינטרנט, עיינו ב-README ב-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
}

שימוש בכתובת IP ציבורית

אם אתם משתמשים בכתובת IP ציבורית כדי להתחבר לאשכול AlloyDB, החליפו את הפונקציה d.Dial בקוד הבא:

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

שימוש ב-Private Service Connect

אם אתם משתמשים ב-Private Service Connect כדי להתחבר למכונה של AlloyDB, צריך לכלול את הפרטים הבאים:

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

אימות אוטומטי ב-IAM

כברירת מחדל, מחברי השפות ל-AlloyDB משתמשים באימות מובנה. אתם יכולים להשתמש באימות אוטומטי ב-IAM עם AlloyDB Go Connector. כדי להפעיל אותה, מחליפים את הפונקציה alloydbconn.NewDialer בקוד הבא:

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

השבתת הטלמטריה המובנית

האפשרות WithOptOutOfBuiltInTelemetry משביתה את הייצוא של המדדים הפנימיים. כברירת מחדל, החייגן מדווח על הפעולות הפנימיות שלו לתחילית המדד של המערכת alloydb.googleapis.com. המדדים האלה עוזרים לשפר את הביצועים של AlloyDB ולזהות בעיות בקישוריות של הלקוח. האפשרות הזו שימושית לאפליקציות שפועלות בסביבות שבהן ייצוא המדדים מוגבל. כדי להשבית את הטלמטריה הזו, צריך לספק את האפשרות הבאה כשמפעילים חייגן:

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

‫Go (מסד נתונים/SQL)

כדי להשתמש ב-AlloyDB Go Connector כדי להתחבר לאשכול AlloyDB, צריך להגדיר את המחבר באמצעות השלבים הבאים, אם משתמשים ב-database/sql.

כדי להשתמש בקטע הקוד הזה בהקשר של אפליקציית אינטרנט, עיינו ב-README ב-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
}

שימוש בכתובת IP ציבורית

אם אתם משתמשים בכתובת IP ציבורית כדי להתחבר לאשכול AlloyDB, החליפו את הפונקציה RegisterDriver בקוד הבא:

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

שימוש ב-Private Service Connect

אם אתם משתמשים ב-Private Service Connect כדי להתחבר למכונה של AlloyDB, צריך לכלול את הפרטים הבאים:

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

אימות אוטומטי ב-IAM

כברירת מחדל, מחברי השפות ל-AlloyDB משתמשים באימות מובנה. אתם יכולים להשתמש באימות אוטומטי ב-IAM עם AlloyDB Go Connector. כדי להפעיל את התכונה, מחליפים את הפונקציה RegisterDriver בקוד הבא:

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

השבתת הטלמטריה המובנית

האפשרות WithOptOutOfBuiltInTelemetry משביתה את הייצוא של המדדים הפנימיים. כברירת מחדל, החייגן מדווח על הפעולות הפנימיות שלו לתחילית המדד של המערכת alloydb.googleapis.com. המדדים האלה עוזרים ל-AlloyDB לשפר את הביצועים ולזהות בעיות בקישוריות של הלקוח. האפשרות הזו שימושית לאפליקציות שפועלות בסביבות שבהן ייצוא המדדים החוצה מוגבל. כדי להשבית את הטלמטריה הזו, צריך לספק את האפשרות הבאה כשמפעילים חייגן:

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