本頁面包含從在 App Engine 標準環境中執行的服務連線至 Cloud SQL 執行個體的資訊與範例。
Cloud SQL 是全代管資料庫服務,可協助您在雲端中設定、維護及管理關聯式資料庫。
App Engine 是全代管的無伺服器平台,適用於大規模開發及託管網頁應用程式。您可以選擇多種常見的語言、程式庫和架構來開發應用程式,然後讓 App Engine 負責根據需求佈建伺服器,以及擴充應用程式執行個體。
設定 Cloud SQL 執行個體
- 在您要連線的 Google Cloud 專案中啟用 Cloud SQL Admin API (如果尚未啟用):
- 建立 PostgreSQL 適用的 Cloud SQL 執行個體。建議您選擇與 Cloud Run 服務位於相同區域的 Cloud SQL
執行個體位置,以縮短延遲時間、避免部分網路費用,並降低跨區域故障風險。
根據預設,Cloud SQL 會為新執行個體指派公開 IP 位址。您也可以選擇指派私人 IP 位址。如要進一步瞭解這兩種連線選項,請參閱「 連線總覽」頁面。
設定 App Engine 標準環境
設定 App Engine 標準環境的步驟取決於您指派給 Cloud SQL 執行個體的 IP 位址類型。公開 IP (預設)
如要設定 App Engine 標準環境,以便使用公開 IP 連線至 Cloud SQL 執行個體,請按照下列步驟操作:
- 請確認執行個體有公開 IP 位址。您可以在 Google Cloud 主控台的「總覽」頁面中,查看執行個體的相關資訊。如果需要新增一個,請參閱「設定公開 IP 頁面」瞭解操作方式。
- 取得執行個體的 INSTANCE_CONNECTION_NAME。您可以在 Google Cloud 主控台的「總覽」頁面中找到此值,也可以執行下列
gcloud sql instances describe
指令來取得: 將 INSTANCE_NAME 改成 Cloud SQL 執行個體的名稱。gcloud sql instances describe INSTANCE_NAME
將 INSTANCE_NAME 變數替換為執行個體名稱。 請確認應用程式用於驗證 Cloud SQL 呼叫的服務帳戶具備
Cloud SQL Client
IAM 角色。如需將身分與存取權管理角色新增至服務帳戶的詳細操作說明,請參閱「為服務帳戶授予角色」一文。
根據預設,應用程式會使用
App Engine 服務帳戶授權連線。服務帳戶身分格式為 PROJECT_ID@appspot.gserviceaccount.com
。
如果授權服務帳戶屬於與 Cloud SQL 執行個體不同的專案,則必須為這兩個專案新增 Cloud SQL Admin API 和 IAM 權限。
私人 IP
如果授權服務帳戶屬於與 Cloud SQL 執行個體所在專案不同的專案,請執行下列操作:
- 在兩個專案中啟用 Cloud SQL Admin API。
- 針對含有 Cloud SQL 執行個體的專案中服務帳戶,新增 IAM 權限。
- 請確認先前建立的 Cloud SQL 執行個體具有私人 IP 位址。如需新增私人 IP,請參閱「設定私人 IP」一文瞭解操作方式。
- 建立無伺服器虛擬私有雲存取連接器,並與 Cloud SQL 執行個體位於相同的虛擬私有雲網路。請注意下列條件:
- 除非您使用 共用虛擬私有雲,否則連接器所在的專案和地區,必須與使用該連接器的資源相同,但連接器可將流量傳送至位於不同地區的資源。
- 針對透過 Cloud VPN 和 虛擬私人雲端網路對等互連連線的虛擬私人雲端網路,無伺服器虛擬私人雲端存取可支援與其通訊。
- 無伺服器虛擬私人雲端存取不支援舊版網路。
- 設定 App Engine 標準環境以使用連接器。
- 使用執行個體的私人 IP 位址和通訊埠
5432
連線。
連線至 Cloud SQL
設定 App Engine 標準環境後,您就可以連線至 Cloud SQL 執行個體。
公開 IP (預設)
針對公開 IP 路徑,App Engine 標準環境會提供加密功能,並透過 Cloud SQL Auth Proxy 以兩種方式建立連線:
- 透過 Unix 通訊端
- 使用 Cloud SQL 連接器
透過 Unix 通訊端連線
設定正確後,您就可以將服務連結至 Cloud SQL 執行個體的 Unix 網域通訊端,並在環境的檔案系統中存取,路徑如下:/cloudsql/INSTANCE_CONNECTION_NAME
。
INSTANCE_CONNECTION_NAME 使用 project:region:instance-id
格式。您可以在 Google Cloud 主控台的「Instance 總覽」頁面中找到此值,也可以執行下列指令來取得:
gcloud sql instances describe [INSTANCE_NAME]
這些連線會自動加密,無須額外設定。
以下程式碼範例是從 GitHub 網站上更完整的範例中擷取。按一下 View on GitHub
即可查看更多資訊。
Python
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
import os
import sqlalchemy
def connect_unix_socket() -> sqlalchemy.engine.base.Engine:
"""Initializes a Unix socket connection pool for a Cloud SQL instance of Postgres."""
# 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_user = os.environ["DB_USER"] # e.g. 'my-database-user'
db_pass = os.environ["DB_PASS"] # e.g. 'my-database-password'
db_name = os.environ["DB_NAME"] # e.g. 'my-database'
unix_socket_path = os.environ[
"INSTANCE_UNIX_SOCKET"
] # e.g. '/cloudsql/project:region:instance'
pool = sqlalchemy.create_engine(
# Equivalent URL:
# postgresql+pg8000://<db_user>:<db_pass>@/<db_name>
# ?unix_sock=<INSTANCE_UNIX_SOCKET>/.s.PGSQL.5432
# Note: Some drivers require the `unix_sock` query parameter to use a different key.
# For example, 'psycopg2' uses the path set to `host` in order to connect successfully.
sqlalchemy.engine.url.URL.create(
drivername="postgresql+pg8000",
username=db_user,
password=db_pass,
database=db_name,
query={"unix_sock": f"{unix_socket_path}/.s.PGSQL.5432"},
),
# ...
)
return pool
Java
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
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 INSTANCE_UNIX_SOCKET = System.getenv("INSTANCE_UNIX_SOCKET");
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 URL is equivalent to setting the config options below:
// jdbc:postgresql:///<DB_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&
// socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=<DB_USER>&password=<DB_PASS>
// 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.setJdbcUrl(String.format("jdbc:postgresql:///%s", DB_NAME));
config.setUsername(DB_USER); // e.g. "root", _postgres"
config.setPassword(DB_PASS); // e.g. "my-password"
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.postgres.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", INSTANCE_CONNECTION_NAME);
// Unix sockets are not natively supported in Java, so it is necessary to use the Cloud SQL
// Java Connector to connect. When setting INSTANCE_UNIX_SOCKET, the connector will
// call an external package that will enable Unix socket connections.
// Note: For Java users, the Cloud SQL Java Connector can provide authenticated connections
// which is usually preferable to using the Cloud SQL Proxy with Unix sockets.
// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
if (INSTANCE_UNIX_SOCKET != null) {
config.addDataSourceProperty("unixSocketPath", INSTANCE_UNIX_SOCKET);
}
// 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);
}
}
Node.js
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
const Knex = require('knex');
// createUnixSocketPool initializes a Unix socket connection pool for
// a Cloud SQL instance of Postgres.
const createUnixSocketPool = 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.
return Knex({
client: 'pg',
connection: {
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance'
},
// ... Specify additional properties here.
...config,
});
};
C#
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
using Npgsql;
using System;
namespace CloudSql
{
public class PostgreSqlUnix
{
public static NpgsqlConnectionStringBuilder NewPostgreSqlUnixSocketConnectionString()
{
// Equivalent connection string:
// "Server=<INSTANCE_UNIX_SOCKET>;Uid=<DB_USER>;Pwd=<DB_PASS>;Database=<DB_NAME>"
var connectionString = new NpgsqlConnectionStringBuilder()
{
// The Cloud SQL proxy provides encryption between the proxy and instance.
SslMode = SslMode.Disable,
// 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.
Host = Environment.GetEnvironmentVariable("INSTANCE_UNIX_SOCKET"), // e.g. '/cloudsql/project:region:instance'
Username = Environment.GetEnvironmentVariable("DB_USER"), // e.g. 'my-db-user
Password = Environment.GetEnvironmentVariable("DB_PASS"), // e.g. 'my-db-password'
Database = Environment.GetEnvironmentVariable("DB_NAME"), // e.g. 'my-database'
};
connectionString.Pooling = true;
// Specify additional properties here.
return connectionString;
}
}
}
Go
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
package cloudsql
import (
"database/sql"
"fmt"
"log"
"os"
// Note: If connecting using the App Engine Flex Go runtime, use
// "github.com/jackc/pgx/stdlib" instead, since v5 requires
// Go modules which are not supported by App Engine Flex.
_ "github.com/jackc/pgx/v5/stdlib"
)
// connectUnixSocket initializes a Unix socket connection pool for
// a Cloud SQL instance of Postgres.
func connectUnixSocket() (*sql.DB, error) {
mustGetenv := func(k string) string {
v := os.Getenv(k)
if v == "" {
log.Fatalf("Fatal Error in connect_unix.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'
unixSocketPath = mustGetenv("INSTANCE_UNIX_SOCKET") // e.g. '/cloudsql/project:region:instance'
dbName = mustGetenv("DB_NAME") // e.g. 'my-database'
)
dbURI := fmt.Sprintf("user=%s password=%s database=%s host=%s",
dbUser, dbPwd, dbName, unixSocketPath)
// dbPool is the pool of database connections.
dbPool, err := sql.Open("pgx", dbURI)
if err != nil {
return nil, fmt.Errorf("sql.Open: %w", err)
}
// ...
return dbPool, nil
}
Ruby
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
unix: &unix
adapter: postgresql
# Configure additional properties here.
# 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: <%= ENV["DB_USER"] %> # e.g. "my-database-user"
password: <%= ENV["DB_PASS"] %> # e.g. "my-database-password"
database: <%= ENV.fetch("DB_NAME") { "vote_development" } %>
# Specify the Unix socket path as host
host: "<%= ENV["INSTANCE_UNIX_SOCKET"] %>"
PHP
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
namespace Google\Cloud\Samples\CloudSQL\Postgres;
use PDO;
use PDOException;
use RuntimeException;
use TypeError;
class DatabaseUnix
{
public static function initUnixDatabaseConnection(): 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'
$instanceUnixSocket = getenv('INSTANCE_UNIX_SOCKET'); // e.g. '/cloudsql/project:region:instance'
// Connect using UNIX sockets
$dsn = sprintf(
'pgsql:dbname=%s;host=%s',
$dbName,
$instanceUnixSocket
);
// 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 $instanceUnixSocket (for UNIX socket mode). ' .
'The PHP error was %s',
$e->getMessage()
),
(int) $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/postgres/connect-external-app',
$e->getMessage()
),
(int) $e->getCode(),
$e
);
}
return $conn;
}
}
使用 Cloud SQL 連接器建立連線
Cloud SQL 連接器是特定語言的程式庫,可在連線至 Cloud SQL 執行個體時提供加密和 IAM 型授權。
Python
如要在網頁應用程式內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
import os
from google.cloud.sql.connector import Connector, IPTypes
import pg8000
import sqlalchemy
def connect_with_connector() -> sqlalchemy.engine.base.Engine:
"""
Initializes a connection pool for a Cloud SQL instance of Postgres.
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["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(refresh_strategy="LAZY")
def getconn() -> pg8000.dbapi.Connection:
conn: pg8000.dbapi.Connection = connector.connect(
instance_connection_name,
"pg8000",
user=db_user,
password=db_pass,
db=db_name,
ip_type=ip_type,
)
return conn
# The Cloud SQL Python Connector can be used with SQLAlchemy
# using the 'creator' argument to 'create_engine'
pool = sqlalchemy.create_engine(
"postgresql+pg8000://",
creator=getconn,
# ...
)
return pool
Java
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
注意:
- CLOUD_SQL_CONNECTION_NAME 應以 <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME> 的格式表示
- 請參閱 這裡 的 JDBC 通訊端處理站版本需求,瞭解 pom.xml 檔案的相關規定。
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 INSTANCE_UNIX_SOCKET = System.getenv("INSTANCE_UNIX_SOCKET");
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 URL is equivalent to setting the config options below:
// jdbc:postgresql:///<DB_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&
// socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=<DB_USER>&password=<DB_PASS>
// 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.setJdbcUrl(String.format("jdbc:postgresql:///%s", DB_NAME));
config.setUsername(DB_USER); // e.g. "root", _postgres"
config.setPassword(DB_PASS); // e.g. "my-password"
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.postgres.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", INSTANCE_CONNECTION_NAME);
// The ipTypes argument can be used to specify a comma delimited list of preferred IP types
// for connecting to a Cloud SQL instance. The argument ipTypes=PRIVATE will force the
// SocketFactory to connect with an instance's associated private IP.
config.addDataSourceProperty("ipTypes", "PUBLIC,PRIVATE");
// 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"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
)
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 passwords and other 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")
)
dsn := fmt.Sprintf("user=%s password=%s database=%s", dbUser, dbPwd, dbName)
config, err := pgx.ParseConfig(dsn)
if err != nil {
return nil, err
}
var opts []cloudsqlconn.Option
if usePrivate != "" {
opts = append(opts, cloudsqlconn.WithDefaultDialOptions(cloudsqlconn.WithPrivateIP()))
}
// 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.
opts = append(opts, cloudsqlconn.WithLazyRefresh())
d, err := cloudsqlconn.NewDialer(context.Background(), opts...)
if err != nil {
return nil, err
}
// Use the Cloud SQL connector to handle connecting to the instance.
// This approach does *NOT* require the Cloud SQL proxy.
config.DialFunc = func(ctx context.Context, network, instance string) (net.Conn, error) {
return d.Dial(ctx, instanceConnectionName)
}
dbURI := stdlib.RegisterConnConfig(config)
dbPool, err := sql.Open("pgx", dbURI)
if err != nil {
return nil, fmt.Errorf("sql.Open: %w", err)
}
return dbPool, nil
}
私人 IP
對於私人 IP 路徑,應用程式會透過虛擬私有雲網路直接連線至執行個體。這個方法會使用 TCP 直接連線至 Cloud SQL 執行個體,不必使用 Cloud SQL 驗證 Proxy。
連線至 TCP
使用 Cloud SQL 執行個體的私人 IP 位址做為主機和通訊埠 5432
進行連線。
Python
如要在網頁應用程式內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
import os
import ssl
import sqlalchemy
def connect_tcp_socket() -> sqlalchemy.engine.base.Engine:
"""Initializes a TCP connection pool for a Cloud SQL instance of Postgres."""
# 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. 5432
pool = sqlalchemy.create_engine(
# Equivalent URL:
# postgresql+pg8000://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name>
sqlalchemy.engine.url.URL.create(
drivername="postgresql+pg8000",
username=db_user,
password=db_pass,
host=db_host,
port=db_port,
database=db_name,
),
# ...
)
return pool
Java
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
注意:
- CLOUD_SQL_CONNECTION_NAME 應以 <MY-PROJECT>:<INSTANCE-REGION>:<INSTANCE-NAME> 的格式表示
- 使用引數 ipTypes=PRIVATE 會強制 SocketFactory 連線至執行個體的相關聯私人 IP
- 請參閱 這裡 的 JDBC 通訊端處理站版本需求,瞭解 pom.xml 檔案的相關規定。
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();
// The following URL is equivalent to setting the config options below:
// jdbc:postgresql://<INSTANCE_HOST>:<DB_PORT>/<DB_NAME>?user=<DB_USER>&password=<DB_PASS>
// 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.setJdbcUrl(String.format("jdbc:postgresql://%s:%s/%s", INSTANCE_HOST, DB_PORT, DB_NAME));
config.setUsername(DB_USER); // e.g. "root", "postgres"
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 Knex = require('knex');
const fs = require('fs');
// createTcpPool initializes a TCP connection pool for a Cloud SQL
// instance of Postgres.
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 = {
client: 'pg',
connection: {
host: process.env.INSTANCE_HOST, // e.g. '127.0.0.1'
port: process.env.DB_PORT, // e.g. '5432'
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
},
// ... Specify additional properties here.
...config,
};
// Establish a connection to the database.
return Knex(dbConfig);
};
Go
如要在網頁應用程式內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
package cloudsql
import (
"database/sql"
"fmt"
"log"
"os"
// Note: If connecting using the App Engine Flex Go runtime, use
// "github.com/jackc/pgx/stdlib" instead, since v5 requires
// Go modules which are not supported by App Engine Flex.
_ "github.com/jackc/pgx/v5/stdlib"
)
// connectTCPSocket initializes a TCP connection pool for a Cloud SQL
// instance of Postgres.
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.", 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. '5432'
dbName = mustGetenv("DB_NAME") // e.g. 'my-database'
)
dbURI := fmt.Sprintf("host=%s user=%s password=%s port=%s database=%s",
dbTCPHost, dbUser, dbPwd, dbPort, dbName)
// dbPool is the pool of database connections.
dbPool, err := sql.Open("pgx", dbURI)
if err != nil {
return nil, fmt.Errorf("sql.Open: %w", err)
}
// ...
return dbPool, nil
}
C#
如要在網頁應用程式的內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
using Npgsql;
using System;
namespace CloudSql
{
public class PostgreSqlTcp
{
public static NpgsqlConnectionStringBuilder NewPostgreSqlTCPConnectionString()
{
// Equivalent connection string:
// "Uid=<DB_USER>;Pwd=<DB_PASS>;Host=<INSTANCE_HOST>;Database=<DB_NAME>;"
var connectionString = new NpgsqlConnectionStringBuilder()
{
// 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.
Host = Environment.GetEnvironmentVariable("INSTANCE_HOST"), // e.g. '127.0.0.1'
// Set Host to 'cloudsql' when deploying to App Engine Flexible environment
Username = Environment.GetEnvironmentVariable("DB_USER"), // e.g. 'my-db-user'
Password = Environment.GetEnvironmentVariable("DB_PASS"), // e.g. 'my-db-password'
Database = Environment.GetEnvironmentVariable("DB_NAME"), // e.g. 'my-database'
// The Cloud SQL proxy provides encryption between the proxy and instance.
SslMode = SslMode.Disable,
};
connectionString.Pooling = true;
// Specify additional properties here.
return connectionString;
}
}
}
Ruby
如要在網頁應用程式內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
tcp: &tcp
adapter: postgresql
# Configure additional properties here.
# 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: <%= ENV["DB_USER"] %> # e.g. "my-database-user"
password: <%= ENV["DB_PASS"] %> # e.g. "my-database-password"
database: <%= ENV.fetch("DB_NAME") { "vote_development" } %>
host: <%= ENV.fetch("INSTANCE_HOST") { "127.0.0.1" }%> # '172.17.0.1' if deployed to GAE Flex
port: <%= ENV.fetch("DB_PORT") { 5432 }%>
PHP
如要在網頁應用程式內容中查看此程式碼片段,請參閱 GitHub 上的 README 檔案。
namespace Google\Cloud\Samples\CloudSQL\Postgres;
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('pgsql:dbname=%s;host=%s', $dbName, $instanceHost);
// 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/postgres/connect-external-app',
$e->getMessage()
),
$e->getCode(),
$e
);
}
return $conn;
}
}
最佳做法和其他資訊
您可以在本機測試應用程式時使用 Cloud SQL 驗證 Proxy。如需詳細操作說明,請參閱快速入門導覽課程:使用 Cloud SQL 驗證 Proxy。
連線集區
資料庫伺服器本身或基礎架構可能會中斷與基礎資料庫的連線。為減輕這種情況,建議您使用支援連線集區和自動重新連線的用戶端程式庫。
連線限制
以 App Engine 標準環境來說,當中運作的執行個體與其他執行個體之間的並行連線數不得超過 100 個。如果是以 PHP 5.5 編寫而成的應用程式,則上限為 60 個並行連線。這項限制適用於每個應用程式執行個體,也就是說,App Engine 應用程式的每個執行個體與資料庫之間的連線數不得超過這個數量。如果擴充執行個體,每項部署作業的總連線數可隨之增加。詳情請參閱「調整元素的資源配置」。
您可以使用連線集區,限制每個執行個體使用的連線數量上限。如需限制連線數量的詳細範例,請參閱「 管理資料庫連線」頁面。
App Engine 應用程式必須符合要求時間限制,實際情況則視用量和環境而定。詳情請參閱 App Engine 標準環境 標準與 彈性環境中的執行個體管理方式。
API 配額限制
App Engine 提供一種機制,可使用 Cloud SQL 驗證 Proxy 進行連線,而這項 Proxy 會使用 Cloud SQL Admin API。 API 配額限制適用於 Cloud SQL 驗證 Proxy。Cloud SQL Admin API 啟動時,會使用兩個配額單位,之後每小時平均使用兩個配額單位。預設配額為每位使用者每分鐘 180 次。App Engine 應用程式也必須符合其他配額與限制的規定,詳情請參閱 App Engine 配額頁面。