mcpField
C
cloudflare-hyperdrive

cloudflare-hyperdrive

github.com/ovachiever云与 DevOps5650 次安装48 周前更新
代码仓库

关于 cloudflare-hyperdrive

cloudflare-hyperdrive 是面向 Cloudflare Workers 开发者的技能,指导将 PostgreSQL 或 MySQL 接入 Worker。内容涵盖连接池、查询缓存、本地开发及私有数据库连接。

主要功能

  1. 01配置 Hyperdrive 和 Worker 绑定
  2. 02连接 PostgreSQL 与 MySQL
  3. 03设置连接池与连接清理
  4. 04使用查询缓存
  5. 05配置 TLS 与私有网络访问

适用场景

  1. 01为 Worker 接入现有数据库
  2. 02在单个请求中执行并行查询
  3. 03通过 Cloudflare Tunnel 访问私有数据库

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ovachiever/droid-tings --skill cloudflare-hyperdrive

安装后在 Claude Code 中输入/cloudflare-hyperdrive确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
.claude-plugin/
plugin.json
references/
connection-pooling.md
drizzle-integration.md
prisma-integration.md
query-caching.md
supported-databases.md
tls-ssl-setup.md
troubleshooting.md
wrangler-commands.md
scripts/
check-versions.sh
templates/
drizzle-mysql.ts
drizzle-postgres.ts
local-dev-setup.sh
mysql2-basic.ts
postgres-basic.ts
postgres-js.ts
postgres-pool.ts
prisma-postgres.ts
wrangler-hyperdrive-config.jsonc

详细介绍

Cloudflare Hyperdrive

状态:生产就绪 ✅ 最后更新:2025-11-23 依赖项:cloudflare-worker-base(推荐用于 Worker 设置) 最新版本:[email protected]、[email protected]+(最低版本)、[email protected]、[email protected]

近期更新(2025):

  • 2025 年 7 月:连接数可配置(最少 5 个,最多约 20 个(Free)/约 100 个(Paid))
  • 2025 年 5 月:缓存命中速度提升 5 倍(区域性预处理语句缓存),获 FedRAMP Moderate 授权
  • 2025 年 4 月:Free 计划开放使用(10 个配置),MySQL 正式支持
  • 2025 年 3 月:延迟降低 90%(连接池部署在数据库附近),IP 访问控制(标准 CF IP 范围)
  • nodejs_compat_v2:pg 驱动程序不再需要 node_compat 模式(compatibility_date 为 2024-09-23 或更高版本时自动启用)
  • 限制:每个账户最多 25 个 Hyperdrive 配置(Paid),每个账户最多 10 个(Free)

快速开始(5 分钟)

1. 创建 Hyperdrive 配置
# For PostgreSQL
npx wrangler hyperdrive create my-postgres-db \
  --connection-string="postgres://user:[email protected]:5432/database"

# For MySQL
npx wrangler hyperdrive create my-mysql-db \
  --connection-string="mysql://user:[email protected]:3306/database"

# Output:
# ✅ Successfully created Hyperdrive configuration
#
# [[hyperdrive]]
# binding = "HYPERDRIVE"
# id = "a76a99bc-7901-48c9-9c15-c4b11b559606"

保存 id 值——下一步会用到!


2. 在 wrangler.jsonc 中配置绑定

在 wrangler.jsonc 中添加:

{
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2024-09-23",
  "compatibility_flags": ["nodejs_compat"],  // REQUIRED for database drivers
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",                     // Available as env.HYPERDRIVE
      "id": "a76a99bc-7901-48c9-9c15-c4b11b559606"  // From wrangler hyperdrive create
    }
  ]
}

重要:

  • 所有数据库驱动程序都必须启用 nodejs_compat 标志
  • binding 用于在代码中访问 Hyperdrive(env.HYPERDRIVE)
  • id 是 Hyperdrive 配置 ID(不是数据库 ID)

3. 安装数据库驱动程序
# For PostgreSQL (choose one)
npm install pg           # node-postgres (most common)
npm install postgres     # postgres.js (modern, minimum v3.4.5)

# For MySQL
npm install mysql2       # mysql2 (minimum v3.13.0)

4. 查询数据库

使用 node-postgres (pg) 连接 PostgreSQL:

import { Client } from "pg";

type Bindings = {
  HYPERDRIVE: Hyperdrive;
};

export default {
  async fetch(request: Request, env: Bindings, ctx: ExecutionContext) {
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString
    });

    await client.connect();

    try {
      const result = await client.query('SELECT * FROM users LIMIT 10');
      return Response.json({ users: result.rows });
    } finally {
      // Clean up connection AFTER response is sent
      ctx.waitUntil(client.end());
    }
  }
};

使用 mysql2 连接 MySQL:

import { createConnection } from "mysql2/promise";

export default {
  async fetch(request: Request, env: Bindings, ctx: ExecutionContext) {
    const connection = await createConnection({
      host: env.HYPERDRIVE.host,
      user: env.HYPERDRIVE.user,
      password: env.HYPERDRIVE.password,
      database: env.HYPERDRIVE.database,
      port: env.HYPERDRIVE.port,
      disableEval: true  // REQUIRED for Workers (eval() not supported)
    });

    try {
      const [rows] = await connection.query('SELECT * FROM users LIMIT 10');
      return Response.json({ users: rows });
    } finally {
      ctx.waitUntil(connection.end());
    }
  }
};

5. 部署
npx wrangler deploy

就是这么简单! 现在,你的 Worker 可以通过 Hyperdrive 连接到现有数据库,并获得以下功能:

  • ✅ 全局连接池
  • ✅ 自动查询缓存
  • ✅ 降低延迟(减少 7 次往返)

Hyperdrive 的工作原理

Hyperdrive 通过以下方式减少 7 次连接往返(TCP + TLS + 身份验证):

  • 在 Worker 附近建立边缘连接(低延迟)
  • 在数据库附近建立连接池(2025 年 3 月:延迟降低 90%)
  • 在边缘缓存查询(2025 年 5 月:缓存命中速度提升 5 倍)

结果:单区域数据库也能像分布式部署一样服务全球。


设置步骤

前提条件
  • 拥有可访问 Workers 的 Cloudflare 账户
  • PostgreSQL(v9.0-17.x)或 MySQL(v5.7-8.x)数据库
  • 数据库可通过公共互联网访问(需要 TLS/SSL),或通过私有网络访问(Cloudflare Tunnel)
  • 2025 年 4 月:Free 计划(10 个配置)和 Paid 计划(25 个配置)均可使用
连接字符串格式
# PostgreSQL
postgres://user:password@host:5432/database
postgres://user:password@host:5432/database?sslmode=require

# MySQL
mysql://user:password@host:3306/database

# URL-encode special chars: p@ssw$rd → p%40ssw%24rd

连接模式

单个连接(pg.Client)
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query('SELECT ...');
ctx.waitUntil(client.end());  // CRITICAL: Non-blocking cleanup

适用于:简单查询,每个请求执行一次查询

连接池(pg.Pool)
const pool = new Pool({
  connectionString: env.HYPERDRIVE.connectionString,
  max: 5  // CRITICAL: Workers limit is 6 connections (July 2025: configurable ~20 Free, ~100 Paid)
});
const [result1, result2] = await Promise.all([
  pool.query('SELECT ...'),
  pool.query('SELECT ...')
]);
ctx.waitUntil(pool.end());

适用于:单个请求中的并行查询

连接清理规则

始终使用 ctx.waitUntil(client.end())——响应发送后进行非阻塞清理 绝不要使用 await client.end()——这会阻塞响应并增加延迟


ORM 集成

Drizzle ORM
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

const sql = postgres(env.HYPERDRIVE.connectionString, { max: 5 });
const db = drizzle(sql);
const allUsers = await db.select().from(users);
ctx.waitUntil(sql.end());
Prisma ORM
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@prisma/client";
import { Pool } from "pg";

const pool = new Pool({ connectionString: env.HYPERDRIVE.connectionString, max: 5 });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
const users = await prisma.user.findMany();
ctx.waitUntil(pool.end());

注意:Prisma 需要驱动适配器(@prisma/adapter-pg)。


本地开发

选项 1:环境变量(推荐)

export CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="postgres://user:password@localhost:5432/local_db"
npx wrangler dev

可以安全提交配置,wrangler.jsonc 中不包含凭据。

选项 2:在 wrangler.jsonc 中使用 localConnectionString

{ "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "prod-id", "localConnectionString": "postgres://..." }] }

⚠️ 不要将凭据提交到版本控制中。

选项 3:远程开发

npx wrangler dev --remote  # ⚠️ Uses PRODUCTION database

查询缓存

会缓存:SELECT(不会修改数据的查询) 不会缓存:INSERT、UPDATE、DELETE、易变函数(LASTVAL、LAST_INSERT_ID)

2025 年 5 月:通过区域性预处理语句缓存,缓存命中速度提升 5 倍。

postgres.js 的重要设置:

const sql = postgres(env.HYPERDRIVE.connectionString, {
  prepare: true  // REQUIRED for caching
});

检查缓存状态:

response.headers.get('cf-cache-status');  // HIT, MISS, BYPASS, EXPIRED

TLS/SSL 配置

SSL 模式:require(默认)、verify-ca(验证 CA)、verify-full(验证 CA 和主机名)

服务器证书(verify-ca/verify-full):

npx wrangler cert upload certificate-authority --ca-cert root-ca.pem --name my-ca-cert
npx wrangler hyperdrive create my-db --connection-string="postgres://..." --ca-certificate-id <ID> --sslmode verify-full

客户端证书(mTLS):

npx wrangler cert upload mtls-certificate --cert client-cert.pem --key client-key.pem --name my-cert
npx wrangler hyperdrive create my-db --connection-string="postgres://..." --mtls-certificate-id <ID>

私有数据库访问(Cloudflare Tunnel)

连接到私有网络(VPC、内部部署)中的数据库:

# 1. Install cloudflared (macOS: brew install cloudflare/cloudflare/cloudflared)
# 2. Create tunnel
cloudflared tunnel create my-db-tunnel

# 3. Configure config.yml
# tunnel: <TUNNEL_ID>
# ingress:
#   - hostname: db.example.com
#     service: tcp://localhost:5432

# 4. Run tunnel
cloudflared tunnel run my-db-tunnel

# 5. Create Hyperdrive
npx wrangler hyperdrive create my-private-db --connection-string="postgres://user:[email protected]:5432/database"

重要规则

务必执行

✅ 在 compatibility_flags 中包含 nodejs_compat ✅ 使用 ctx.waitUntil(client.end()) 清理连接 ✅ 将连接池的 max 设为 5(Workers 限制:6) ✅ 为数据库启用 TLS/SSL(Hyperdrive 要求启用) ✅ 使用预处理语句进行缓存(postgres.js:prepare: true) ✅ 为 mysql2 驱动设置 disableEval: true ✅ 使用 try/catch 妥善处理错误 ✅ 在本地开发时使用环境变量设置连接字符串 ✅ 部署前使用 wrangler dev 在本地测试

务必避免

❌ 跳过 nodejs_compat 标志(会导致 “No such module” 错误) ❌ 直接使用私有 IP 地址(请改用 Cloudflare Tunnel) ❌ 使用 await client.end()(会阻塞响应,请改用 ctx.waitUntil()) ❌ 将连接池的 max 设为大于 5(超过 Workers 的 6 个连接限制) ❌ 将所有查询都包装在事务中(会限制连接多路复用) ❌ 使用 SQL 级别的 PREPARE/EXECUTE/DEALLOCATE(不受支持) ❌ 使用 advisory locks、LISTEN/NOTIFY(PostgreSQL 不支持这些功能) ❌ 在 MySQL 中使用多语句查询(不受支持) ❌ 将数据库凭据提交到版本控制中


Wrangler 命令参考

# Create Hyperdrive configuration
wrangler hyperdrive create <name> --connection-string="postgres://..."

# List all Hyperdrive configurations
wrangler hyperdrive list

# Get details of a configuration
wrangler hyperdrive get <hyperdrive-id>

# Update connection string
wrangler hyperdrive update <hyperdrive-id> --connection-string="postgres://..."

# Delete configuration
wrangler hyperdrive delete <hyperdrive-id>

# Upload CA certificate
wrangler cert upload certificate-authority --ca-cert <file>.pem --name <name>

# Upload client certificate pair
wrangler cert upload mtls-certificate --cert <cert>.pem --key <key>.pem --name <name>

支持的数据库

PostgreSQL(v9.0-17.x):AWS RDS/Aurora、Google Cloud SQL、Azure、Neon、Supabase、PlanetScale、Timescale、CockroachDB、Materialize、Fly.io、pgEdge、Prisma Postgres

MySQL(v5.7-8.x):AWS RDS/Aurora、Google Cloud SQL、Azure、PlanetScale、MariaDB(2025 年 4 月正式发布)

不支持:SQL Server、MongoDB、Oracle


不支持的功能

PostgreSQL
  • SQL 级别的预处理语句(PREPARE、EXECUTE、DEALLOCATE)
  • Advisory locks
  • LISTEN 和 NOTIFY
  • 修改每个会话的状态
MySQL
  • 查询中的非 UTF-8 字符
  • USE 语句
  • 多语句查询
  • 协议级别的预处理语句(COM_STMT_PREPARE)
  • COM_INIT_DB 消息
  • 除 caching_sha2_password 或 mysql_native_password 以外的身份验证插件

解决方法:对于不支持的功能,请创建第二个直接客户端连接(不经过 Hyperdrive)。


性能最佳实践

  1. 避免长时间运行的事务 - 会限制连接多路复用
  2. 使用预处理语句 - 启用查询缓存(postgres.js:prepare: true)
  3. 将连接池的 max 设为 5 - 确保不超过 Workers 的 6 个连接限制
  4. 不需要时禁用 fetch_types - 降低延迟(postgres.js)
  5. 使用 ctx.waitUntil() 清理连接 - 非阻塞地关闭连接
  6. 使用适合缓存的查询 - 优先使用 SELECT,而非复杂的连接查询
  7. 为经常查询的列创建索引 - 提升查询性能
  8. 使用 Hyperdrive 分析进行监控 - 跟踪缓存命中率和延迟

故障排除

请参阅 references/troubleshooting.md,查看包含解决方案的完整错误参考。

快速修复:

错误解决方案
"No such module 'node:*'"将 nodejs_compat 添加到 compatibility_flags
"TLS not supported by database"为数据库启用 SSL/TLS
"Connection refused"检查防火墙规则,允许连接公共互联网或使用 Tunnel
"Failed to acquire connection"使用 ctx.waitUntil() 清理连接,避免长时间运行的事务
"Code generation from strings disallowed"在 mysql2 配置中设置 disableEval: true
"Bad hostname"确认 DNS 可以解析,检查是否有拼写错误
"Invalid database credentials"检查用户名/密码(区分大小写)

指标和分析

Hyperdrive 仪表板 → 选择配置 → Metrics 标签页

可用指标:查询数量、缓存命中率、查询延迟(p50/p95/p99)、连接延迟、查询/结果字节数、错误率


凭据轮换

# Option 1: Create new config (zero downtime)
wrangler hyperdrive create my-db-v2 --connection-string="postgres://new-creds..."
# Update wrangler.jsonc, deploy, delete old config

# Option 2: Update existing
wrangler hyperdrive update <id> --connection-string="postgres://new-creds..."

最佳实践:为预发布环境和生产环境使用单独的配置。


参考资料


最后更新:2025-11-23 软件包版本:[email protected],[email protected]+(最低版本),[email protected],[email protected] 生产环境测试:基于 Cloudflare 官方文档和社区示例

评论

支持 Markdown