本示例展示如何将 Hyperdrive 连接到 Google Cloud SQL Postgres 数据库实例。
要允许 Hyperdrive 连接数据库,需确保 Hyperdrive 拥有有效用户凭据和网络访问权限。
在 Google Cloud Console ↗ 中创建实例或编辑现有实例时:
要允许 Hyperdrive 访问实例:
- 在 Cloud Console ↗ 中,选择希望 Hyperdrive 连接的实例。
- 展开 Connections(连接) > Networking(网络) > 确保已启用 Public IP(公共 IP) > Add a Network(添加网络) 并输入
0.0.0.0/0。 - 选择 Done(完成) > Save(保存) 保存更改。
- 在侧边栏选择 Overview(概览),记下实例的 Public IP address(公网 IP 地址)。
要创建 Hyperdrive 连接用户:
- 在侧边栏选择 Users(用户)。
- 选择 Add User Account(添加用户账户) > 选择 Built-in authentication(内置身份验证)。
- 输入名称(例如
hyperdrive-user)> 选择 Generate(生成) 生成密码。 - 在选择 Add(添加) 创建用户前,将此密码复制到剪贴板。
有了用户名、密码、公网 IP 地址和(可选)数据库名称(默认:postgres)后,即可创建 Hyperdrive 数据库配置。
gcloud CLI ↗ 可创建新用户并允许 Hyperdrive 连接数据库。
使用 gcloud sql 创建具有强密码的新用户(例如 hyperdrive-user):
gcloud sql users create hyperdrive-user --instance=YOUR_INSTANCE_NAME --password=SUFFICIENTLY_LONG_PASSWORD运行以下命令为数据库实例启用互联网访问 ↗:
# If you have any existing authorized networks, ensure you provide those as a comma separated list.
# The gcloud CLI will replace any existing authorized networks with the list you provide here.
gcloud sql instances patch YOUR_INSTANCE_NAME --authorized-networks="0.0.0.0/0"请参阅 Google Cloud 文档 ↗ 了解其他配置选项。
配置 Hyperdrive 需要:
- 数据库的 IP 地址(或主机名)和端口。
- 上一步配置的数据库用户名(例如
hyperdrive-demo)。 - 该用户名对应的密码。
- 希望 Hyperdrive 连接的数据库名称,例如
postgres。
Hyperdrive 接受数据库驱动常用的连接字符串格式组合上述参数:
postgres://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name大多数数据库提供商会提供可直接复制到 Hyperdrive 的连接字符串。
在 Cloudflare 仪表板中创建 Hyperdrive 配置:
-
在 Cloudflare 仪表板中,前往 Hyperdrive 页面。
Go to Hyperdrive ↗ -
选择 Create Configuration(创建配置)。
-
填写表单,包括连接字符串。
-
选择 Create(创建)。
使用 Wrangler CLI 创建 Hyperdrive 配置:
-
打开终端并运行以下命令。将
<NAME_OF_HYPERDRIVE_CONFIG>替换为 Hyperdrive 配置名称,并粘贴数据库主机提供的连接字符串,或将user、password、HOSTNAME_OR_IP_ADDRESS、port和database_name占位符替换为你的数据库信息:npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name" -
该命令会输出 Wrangler 配置文件 的绑定:
{ "$schema": "./node_modules/wrangler/config-schema.json", "name": "hyperdrive-example", "main": "src/index.ts", // Set this to today's date "compatibility_date": "2026-08-17", "compatibility_flags": [ "nodejs_compat" ], // Pasted from the output of `wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string=[...]` above. "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>" } ] }"$schema" = "./node_modules/wrangler/config-schema.json" name = "hyperdrive-example" main = "src/index.ts" # Set this to today's date compatibility_date = "2026-08-17" compatibility_flags = [ "nodejs_compat" ] [[hyperdrive]] binding = "HYPERDRIVE" id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"
安装 node-postgres 驱动:
npm i pg@>8.16.3yarn add pg@>8.16.3pnpm add pg@>8.16.3bun add pg@>8.16.3若使用 TypeScript,安装类型包:
npm i -D @types/pgyarn add -D @types/pgpnpm add -D @types/pgbun add -d @types/pg在 wrangler.jsonc 中添加所需的 Node.js 兼容性标志和 Hyperdrive 绑定:
在 wrangler.jsonc 中添加 Node.js 兼容性标志和 Hyperdrive 绑定(binding):
{
// required for database drivers to function
"compatibility_flags": [
"nodejs_compat"
],
// Set this to today's date
"compatibility_date": "2026-08-17",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"创建新的 Client 实例并传入 Hyperdrive connectionString:
// filepath: src/index.ts
import { Client } from "pg";
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
// Create a new client instance for each request. Hyperdrive maintains the
// underlying database connection pool, so creating a new client is fast.
const client = new Client({
connectionString: env.HYPERDRIVE.connectionString,
});
try {
// Connect to the database
await client.connect();
// Perform a simple query
const result = await client.query("SELECT * FROM pg_tables");
return Response.json({
success: true,
result: result.rows,
});
} catch (error: any) {
console.error("Database error:", error.message);
return new Response("Internal error occurred", { status: 500 });
}
},
};- 了解更多 Hyperdrive 工作原理。
- 参阅故障排除指南以排查常见问题。
- 进一步了解 Cloudflare Workers 可用的其他存储选项。