從 Cloud Run 函式連線

本頁面提供相關資訊和範例,說明如何從 Cloud Run functions 中執行的服務,連線至 Cloud SQL 執行個體。

如需逐步說明,瞭解如何執行連線至 Cloud SQL 的 Cloud Run functions 範例網頁應用程式,請參閱從 Cloud Run functions 連線的快速入門導覽課程。

Cloud SQL 是全代管資料庫服務,可協助您在雲端設定、維護及管理關聯式資料庫。

Cloud Run functions 是一項簡易運算解決方案,可讓開發人員建立獨立的單一用途函式來回應雲端事件,而不需要管理伺服器或執行階段環境。

設定 Cloud SQL 執行個體

  1. 在連線來源的 Google Cloud 專案中啟用 Cloud SQL Admin API (如果尚未啟用):

    啟用 API 所需的角色

    如要啟用 API,您必須具備 serviceusage.services.enable 權限。如果您建立了專案,可能已透過擁有者角色 (roles/owner) 取得這項權限。否則,您可以透過服務使用情形管理員角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    啟用 API

  2. 建立 SQL Server 適用的 Cloud SQL 執行個體。建議您選擇與 Cloud Run functions 服務位於相同區域的 Cloud SQL 執行個體位置,以縮短延遲時間、避免產生部分網路費用,並降低跨區域故障風險。

    根據預設,Cloud SQL 會為新執行個體指派公開 IP 位址。您也可以選擇指派私人 IP 位址。如要進一步瞭解兩者的連線選項,請參閱「 連線總覽」頁面。

  3. 建立執行個體時,您可以選擇執行個體的 伺服器憑證 (CA) 階層,然後將階層設為執行個體的 serverCaMode。如要從網頁應用程式連線至執行個體,請務必選取個別執行個體 CA 選項 (GOOGLE_MANAGED_INTERNAL_CA) 做為伺服器 CA 模式。

設定 Cloud Run 函式

設定 Cloud Run 函式的步驟,取決於您指派給 Cloud SQL 執行個體的 IP 位址類型。

公開 IP (預設)

Cloud Run functions 支援使用 Go、Java 和 Python 連接器,透過公開 IP 連線至 SQL Server 適用的 Cloud SQL。

如要設定 Cloud Run functions,啟用與 Cloud SQL 執行個體的連線,請按照下列步驟操作:
  • 確認上述建立的執行個體具有公開 IP 位址。您可以在Google Cloud 控制台的執行個體「Overview」(總覽) 頁面確認這項資訊。如要新增公開 IP 位址,請參閱「設定公開 IP」。
  • 取得執行個體的 INSTANCE_CONNECTION_NAME。這個值適用於:
    • 在Google Cloud 控制台的執行個體「Overview」(總覽) 頁面中,或
    • 執行下列指令: gcloud sql instances describe [INSTANCE_NAME]
  • 設定函式的服務帳戶。如果授權服務帳戶與 Cloud SQL 執行個體屬於不同專案,則必須啟用 Cloud SQL Admin API,並將 Cloud SQL Client IAM 角色新增至這兩項專案。
  • 確認服務帳戶具備這個角色,以便連結至 Cloud SQL。
  • 如果您使用的是 Cloud Run functions,而非 Cloud Run functions (第 1 代),則必須符合下列條件 (另請參閱「 設定 Cloud Run」):
    1. 一開始部署函式。
      首次在 Google Cloud 控制台建立 Cloud Run 函式時,基礎 Cloud Run 服務尚未建立。您必須先建立該服務 (方法是部署 Cloud Run 函式),才能設定 Cloud SQL 連線。
    2. 在 Google Cloud 控制台的「Function details」(函式詳細資料) 頁面右上角,按一下「Powered by Cloud Run」(採用 Cloud Run 技術) 下方的連結,存取基礎 Cloud Run 服務。
    3. 在 Cloud Run 的「Service details」(服務詳細資料) 頁面中,選取「Edit and deploy new revision」(編輯並部署新的修訂版本) 分頁標籤。
    4. 請按照標準步驟 (與任何設定變更的情況相同),為 Cloud SQL 連線設定新設定。
      這項操作會建立新的 Cloud Run 修訂版本,後續修訂版本會自動接收這個 Cloud SQL 連線,除非您明確變更。

私人 IP

如果授權服務帳戶和 Cloud SQL 執行個體位於不同專案,請執行下列操作:

  • 在兩項專案中啟用 Cloud SQL Admin API。
  • 在含有 Cloud SQL 執行個體的專案中,為服務帳戶新增 IAM 權限。
無伺服器 VPC 存取連接器會使用私人 IP 位址,處理與虛擬私有雲網路之間的通訊。 如要直接使用私人 IP 位址連線,請務必執行下列操作:
  1. 確認先前建立的 Cloud SQL 執行個體具有私人 IP 位址。如需新增,請參閱設定私人 IP 的操作說明。
  2. 在 Cloud SQL 執行個體所在的虛擬私有雲網路中,建立無伺服器 VPC 存取連接器。請注意下列條件:
    • 除非您使用 Shared VPC,否則連接器必須與使用連接器的資源位於相同專案和區域,但可以將流量傳送至不同區域的資源。
    • 無伺服器 VPC 存取支援與使用 Cloud VPN 和虛擬私有雲網路對接連線的虛擬私有雲網路通訊。
    • 無伺服器 VPC 存取不支援舊版網路。
  3. 設定 Cloud Run functions 以使用連接器。
  4. 使用執行個體的私人 IP 位址和通訊埠 1433 進行連線。

連線至 Cloud SQL

設定 Cloud Run 函式後,即可連線至 Cloud SQL 執行個體。

公開 IP (預設)

如果是公開 IP 路徑,Cloud Run functions 會提供加密功能,並使用 Cloud SQL 連接器連線。

使用 Cloud SQL 連接器連線

Cloud SQL 連接器是特定語言的程式庫,可在連線至 Cloud SQL 執行個體時提供加密和 IAM 授權。

Python

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

import os

from google.cloud.sql.connector import Connector, IPTypes
import pytds

import sqlalchemy


def connect_with_connector() -> sqlalchemy.engine.base.Engine:
    """
    Initializes a connection pool for a Cloud SQL instance of SQL Server.

    Uses the Cloud SQL Python Connector package.
    """
    # Note: Saving credentials in environment variables is convenient, but not
    # secure - consider a more secure solution such as
    # Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
    # keep secrets safe.

    instance_connection_name = os.environ[
        "INSTANCE_CONNECTION_NAME"
    ]  # e.g. 'project:region:instance'
    db_user = os.environ.get("DB_USER", "")  # e.g. 'my-db-user'
    db_pass = os.environ["DB_PASS"]  # e.g. 'my-db-password'
    db_name = os.environ["DB_NAME"]  # e.g. 'my-database'

    ip_type = IPTypes.PRIVATE if os.environ.get("PRIVATE_IP") else IPTypes.PUBLIC

    # initialize Cloud SQL Python Connector object
    connector = Connector(ip_type=ip_type, refresh_strategy="LAZY")

    connect_args = {}
    # If your SQL Server instance requires SSL, you need to download the CA
    # certificate for your instance and include cafile={path to downloaded
    # certificate} and validate_host=False. This is a workaround for a known issue.
    if os.environ.get("DB_ROOT_CERT"):  # e.g. '/path/to/my/server-ca.pem'
        connect_args = {
            "cafile": os.environ["DB_ROOT_CERT"],
            "validate_host": False,
        }

    def getconn() -> pytds.Connection:
        conn = connector.connect(
            instance_connection_name,
            "pytds",
            user=db_user,
            password=db_pass,
            db=db_name,
            **connect_args
        )
        return conn

    pool = sqlalchemy.create_engine(
        "mssql+pytds://",
        creator=getconn,
        # ...
    )
    return pool

Java

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

注意:

  • CLOUD_SQL_CONNECTION_NAME 應以 <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME> 表示
  • 如要瞭解 pom.xml 檔案的 JDBC Socket Factory 版本需求,請參閱 這裡 。


import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;

public class ConnectorConnectionPoolFactory extends ConnectionPoolFactory {

  // Note: Saving credentials in environment variables is convenient, but not
  // secure - consider a more secure solution such as
  // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
  // keep secrets safe.
  private static final String INSTANCE_CONNECTION_NAME =
      System.getenv("INSTANCE_CONNECTION_NAME");
  private static final String DB_USER = System.getenv("DB_USER");
  private static final String DB_PASS = System.getenv("DB_PASS");
  private static final String DB_NAME = System.getenv("DB_NAME");

  public static DataSource createConnectionPool() {
    // The configuration object specifies behaviors for the connection pool.
    HikariConfig config = new HikariConfig();

    // The following is equivalent to setting the config options below:
    // jdbc:sqlserver://;user=<DB_USER>;password=<DB_PASS>;databaseName=<DB_NAME>;
    // socketFactoryClass=com.google.cloud.sql.sqlserver.SocketFactory;
    // socketFactoryConstructorArg=<INSTANCE_CONNECTION_NAME>

    // See the link below for more info on building a JDBC URL for the Cloud SQL JDBC Socket Factory
    // https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory#creating-the-jdbc-url

    // Configure which instance and what database user to connect with.
    config
        .setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDataSource");
    config.setUsername(DB_USER); // e.g. "root", "sqlserver"
    config.setPassword(DB_PASS); // e.g. "my-password"
    config.addDataSourceProperty("databaseName", DB_NAME);

    config.addDataSourceProperty("socketFactoryClass",
        "com.google.cloud.sql.sqlserver.SocketFactory");
    config.addDataSourceProperty("socketFactoryConstructorArg", INSTANCE_CONNECTION_NAME);

    // The Java Connector provides SSL encryption, so it should be disabled
    // at the driver level.
    config.addDataSourceProperty("encrypt", "false");

    // cloudSqlRefreshStrategy set to "lazy" is used to perform a
    // refresh when needed, rather than on a scheduled interval.
    // This is recommended for serverless environments to
    // avoid background refreshes from throttling CPU.
    config.addDataSourceProperty("cloudSqlRefreshStrategy", "lazy");

    // ... Specify additional connection properties here.
    // ...

    // Initialize the connection pool using the configuration object.
    return new HikariDataSource(config);
  }
}

Go

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

package cloudsql

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"net"
	"os"

	"cloud.google.com/go/cloudsqlconn"
	mssql "github.com/denisenkom/go-mssqldb"
)

type csqlDialer struct {
	dialer     *cloudsqlconn.Dialer
	connName   string
	usePrivate bool
}

// DialContext adheres to the mssql.Dialer interface.
func (c *csqlDialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
	var opts []cloudsqlconn.DialOption
	if c.usePrivate {
		opts = append(opts, cloudsqlconn.WithPrivateIP())
	}
	return c.dialer.Dial(ctx, c.connName, opts...)
}

func connectWithConnector() (*sql.DB, error) {
	mustGetenv := func(k string) string {
		v := os.Getenv(k)
		if v == "" {
			log.Fatalf("Fatal Error in connect_connector.go: %s environment variable not set.\n", k)
		}
		return v
	}
	// Note: Saving credentials in environment variables is convenient, but not
	// secure - consider a more secure solution such as
	// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
	// keep secrets safe.
	var (
		dbUser                 = mustGetenv("DB_USER")                  // e.g. 'my-db-user'
		dbPwd                  = mustGetenv("DB_PASS")                  // e.g. 'my-db-password'
		dbName                 = mustGetenv("DB_NAME")                  // e.g. 'my-database'
		instanceConnectionName = mustGetenv("INSTANCE_CONNECTION_NAME") // e.g. 'project:region:instance'
		usePrivate             = os.Getenv("PRIVATE_IP")
	)

	dbURI := fmt.Sprintf("user id=%s;password=%s;database=%s;", dbUser, dbPwd, dbName)
	c, err := mssql.NewConnector(dbURI)
	if err != nil {
		return nil, fmt.Errorf("mssql.NewConnector: %w", err)
	}
	// WithLazyRefresh() Option is used to perform refresh
	// when needed, rather than on a scheduled interval.
	// This is recommended for serverless environments to
	// avoid background refreshes from throttling CPU.
	dialer, err := cloudsqlconn.NewDialer(context.Background(), cloudsqlconn.WithLazyRefresh())
	if err != nil {
		return nil, fmt.Errorf("cloudsqlconn.NewDailer: %w", err)
	}
	c.Dialer = &csqlDialer{
		dialer:     dialer,
		connName:   instanceConnectionName,
		usePrivate: usePrivate != "",
	}

	dbPool := sql.OpenDB(c)
	if err != nil {
		return nil, fmt.Errorf("sql.Open: %w", err)
	}
	return dbPool, nil
}

Node.js

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

const {Connection} = require('tedious');
const {Connector} = require('@google-cloud/cloud-sql-connector');

// In case the PRIVATE_IP environment variable is defined then we set
// the ipType=PRIVATE for the new connector instance, otherwise defaults
// to public ip type.
const getIpType = () =>
  process.env.PRIVATE_IP === '1' || process.env.PRIVATE_IP === 'true'
    ? 'PRIVATE'
    : 'PUBLIC';

// connectWithConnector initializes a TCP connection
// to a Cloud SQL instance of SQL Server.
const connectWithConnector = async config => {
  // Note: Saving credentials in environment variables is convenient, but not
  // secure - consider a more secure solution such as
  // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
  // keep secrets safe.
  const connector = new Connector();
  const clientOpts = await connector.getTediousOptions({
    instanceConnectionName: process.env.INSTANCE_CONNECTION_NAME,
    ipType: getIpType(),
  });
  const dbConfig = {
    // Please note that the `server` property here is not used and is only
    // defined due to a bug in the tedious driver
    // (ref: https://github.com/tediousjs/tedious/issues/1541)
    // With that in mind, do not try to change this value since it will have no
    // impact in how the connector works, this sample will be updated to remove
    // this property declaration as soon as the tedious driver bug is fixed
    server: '0.0.0.0', // e.g. '127.0.0.1'
    authentication: {
      type: 'default',
      options: {
        userName: process.env.DB_USER, // e.g. 'my-db-user'
        password: process.env.DB_PASS, // e.g. 'my-db-password'
      },
    },
    options: {
      ...clientOpts,
      // Please note that the `port` property here is not used and is only
      // defined due to a bug in the tedious driver
      // (ref: https://github.com/tediousjs/tedious/issues/1541)
      // With that in mind, do not try to change this value since it will have
      // no impact in how the connector works, this sample will be updated to
      // remove this property declaration as soon as the tedious driver bug is
      // fixed
      port: 9999,
      database: process.env.DB_NAME, // e.g. 'my-database'
      useColumnNames: true,
    },
    // ... Specify additional properties here.
    ...config,
  };

  // Establish a connection to the database.
  return new Connection(dbConfig);
};

私人 IP

如果是私人 IP 路徑,應用程式會透過虛擬私有雲網路直接連線至執行個體。這個方法會使用 TCP 直接連線至 Cloud SQL 執行個體,不使用 Cloud SQL Auth Proxy。

使用 TCP 連線

使用 Cloud SQL 執行個體的私人 IP 位址做為主機和通訊埠 1433 進行連線。

Python

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

import os

import sqlalchemy


def connect_tcp_socket() -> sqlalchemy.engine.base.Engine:
    """Initializes a TCP connection pool for a Cloud SQL instance of SQL Server."""
    # Note: Saving credentials in environment variables is convenient, but not
    # secure - consider a more secure solution such as
    # Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
    # keep secrets safe.
    db_host = os.environ[
        "INSTANCE_HOST"
    ]  # e.g. '127.0.0.1' ('172.17.0.1' if deployed to GAE Flex)
    db_user = os.environ["DB_USER"]  # e.g. 'my-db-user'
    db_pass = os.environ["DB_PASS"]  # e.g. 'my-db-password'
    db_name = os.environ["DB_NAME"]  # e.g. 'my-database'
    db_port = os.environ["DB_PORT"]  # e.g. 1433

    pool = sqlalchemy.create_engine(
        # Equivalent URL:
        # mssql+pytds://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name>
        sqlalchemy.engine.url.URL.create(
            drivername="mssql+pytds",
            username=db_user,
            password=db_pass,
            database=db_name,
            host=db_host,
            port=db_port,
        ),
        # ...
    )

    return pool

Java

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

注意:


import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;

public class TcpConnectionPoolFactory extends ConnectionPoolFactory {

  // Note: Saving credentials in environment variables is convenient, but not
  // secure - consider a more secure solution such as
  // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
  // keep secrets safe.
  private static final String DB_USER = System.getenv("DB_USER");
  private static final String DB_PASS = System.getenv("DB_PASS");
  private static final String DB_NAME = System.getenv("DB_NAME");

  private static final String INSTANCE_HOST = System.getenv("INSTANCE_HOST");
  private static final String DB_PORT = System.getenv("DB_PORT");


  public static DataSource createConnectionPool() {
    // The configuration object specifies behaviors for the connection pool.
    HikariConfig config = new HikariConfig();

    // Configure which instance and what database user to connect with.
    config.setJdbcUrl(
        String.format("jdbc:sqlserver://%s:%s;databaseName=%s", INSTANCE_HOST, DB_PORT, DB_NAME));
    config.setUsername(DB_USER); // e.g. "root", "sqlserver"
    config.setPassword(DB_PASS); // e.g. "my-password"


    // ... Specify additional connection properties here.
    // ...

    // Initialize the connection pool using the configuration object.
    return new HikariDataSource(config);
  }
}

Node.js

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

const mssql = require('mssql');

// createTcpPool initializes a TCP connection pool for a Cloud SQL
// instance of SQL Server.
const createTcpPool = async config => {
  // Note: Saving credentials in environment variables is convenient, but not
  // secure - consider a more secure solution such as
  // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
  // keep secrets safe.
  const dbConfig = {
    server: process.env.INSTANCE_HOST, // e.g. '127.0.0.1'
    port: parseInt(process.env.DB_PORT), // e.g. 1433
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    options: {
      trustServerCertificate: true,
    },
    // ... Specify additional properties here.
    ...config,
  };
  // Establish a connection to the database.
  return mssql.connect(dbConfig);
};

Go

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

package cloudsql

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"strings"

	_ "github.com/denisenkom/go-mssqldb"
)

// connectTCPSocket initializes a TCP connection pool for a Cloud SQL
// instance of SQL Server.
func connectTCPSocket() (*sql.DB, error) {
	mustGetenv := func(k string) string {
		v := os.Getenv(k)
		if v == "" {
			log.Fatalf("Fatal Error in connect_tcp.go: %s environment variable not set.\n", k)
		}
		return v
	}
	// Note: Saving credentials in environment variables is convenient, but not
	// secure - consider a more secure solution such as
	// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
	// keep secrets safe.
	var (
		dbUser    = mustGetenv("DB_USER")       // e.g. 'my-db-user'
		dbPwd     = mustGetenv("DB_PASS")       // e.g. 'my-db-password'
		dbTCPHost = mustGetenv("INSTANCE_HOST") // e.g. '127.0.0.1' ('172.17.0.1' if deployed to GAE Flex)
		dbPort    = mustGetenv("DB_PORT")       // e.g. '1433'
		dbName    = mustGetenv("DB_NAME")       // e.g. 'my-database'
	)

	dbURI := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%s;database=%s;",
		dbTCPHost, dbUser, dbPwd, dbPort, dbName)


	// dbPool is the pool of database connections.
	dbPool, err := sql.Open("sqlserver", dbURI)
	if err != nil {
		return nil, fmt.Errorf("sql.Open: %w", err)
	}

	// ...

	return dbPool, nil
}

PHP

如要查看網頁應用程式中的程式碼片段,請參閱 GitHub 上的 README。

namespace Google\Cloud\Samples\CloudSQL\SQLServer;

use PDO;
use PDOException;
use RuntimeException;
use TypeError;

class DatabaseTcp
{
    public static function initTcpDatabaseConnection(): PDO
    {
        try {
            // Note: Saving credentials in environment variables is convenient, but not
            // secure - consider a more secure solution such as
            // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
            // keep secrets safe.
            $username = getenv('DB_USER'); // e.g. 'your_db_user'
            $password = getenv('DB_PASS'); // e.g. 'your_db_password'
            $dbName = getenv('DB_NAME'); // e.g. 'your_db_name'
            $instanceHost = getenv('INSTANCE_HOST'); // e.g. '127.0.0.1' ('172.17.0.1' for GAE Flex)

            // Connect using TCP
            $dsn = sprintf(
                'sqlsrv:server=%s;Database=%s',
                $instanceHost,
                $dbName
            );

            // Connect to the database
            $conn = new PDO(
                $dsn,
                $username,
                $password,
                # ...
            );
        } catch (TypeError $e) {
            throw new RuntimeException(
                sprintf(
                    'Invalid or missing configuration! Make sure you have set ' .
                        '$username, $password, $dbName, and $instanceHost (for TCP mode). ' .
                        'The PHP error was %s',
                    $e->getMessage()
                ),
                $e->getCode(),
                $e
            );
        } catch (PDOException $e) {
            throw new RuntimeException(
                sprintf(
                    'Could not connect to the Cloud SQL Database. Check that ' .
                        'your username and password are correct, that the Cloud SQL ' .
                        'proxy is running, and that the database exists and is ready ' .
                        'for use. For more assistance, refer to %s. The PDO error was %s',
                    'https://cloud.google.com/sql/docs/sqlserver/connect-external-app',
                    $e->getMessage()
                ),
                (int) $e->getCode(),
                $e
            );
        }

        return $conn;
    }
}

最佳做法和其他資訊

在本機測試應用程式時,可以使用 Cloud SQL Auth Proxy。如需詳細操作說明,請參閱快速入門導覽課程:使用 Cloud SQL Auth Proxy。

連線集區

基礎資料庫的連線可能會中斷,原因可能是資料庫伺服器本身,或 Cloud Run 函式的基礎架構。建議使用支援連線集區的用戶端程式庫,自動重新連線中斷的用戶端連線。此外,建議您使用全域範圍的連線集區,提高函式在後續叫用時重複使用相同連線的可能性,並在執行個體遭到淘汰 (自動縮減) 時自然關閉連線。如需如何使用連線集區的詳細範例,請參閱「管理資料庫連線」。

連線限制

Cloud SQL 會限制並行連線數量上限,這些限制可能因所選資料庫引擎而異 (請參閱「Cloud SQL 配額和限制」)。

建議您搭配 Cloud Run 函式使用連線集區,但請務必將連線數量上限設為 1。

請盡可能只為需要存取資料庫的函式初始化連線集區。部分連線集區會預先建立連線,這可能會耗用過多資源,並計入連線限制。因此,建議您使用 延遲初始化,將連線集區的建立作業延遲到需要時再執行,並只在會用到連線集區的函式中加入連線集區。

如需如何限制連線數量的詳細範例,請參閱「管理資料庫連線」。

API 配額限制

Cloud Run functions 提供使用 Cloud SQL Auth Proxy 連線的機制,該 Proxy 會使用 Cloud SQL Admin API。Cloud SQL Auth Proxy 適用 API 配額限制。Cloud SQL Admin API 配額用量約為設定的 Cloud SQL 執行個體數量乘以部署的函式總數,再乘以二。您可以設定並行叫用次數上限,修改預期的 API 配額用量。Cloud Run functions 也會對每 100 秒允許的 API 呼叫次數設定頻率限制。

後續步驟