CloudflareHyperdrive数据库连接与加速技能 cloudflare-hyperdrive

Cloudflare Hyperdrive 是一种用于在 Cloudflare Workers 中连接和管理 PostgreSQL 或 MySQL 数据库的服务,提供全局连接池和查询缓存功能,优化数据库访问性能,降低延迟,支持多种数据库驱动和 ORM。关键词:Cloudflare Hyperdrive, Workers, 数据库连接, 连接池, 查询缓存, PostgreSQL, MySQL, 云原生, Serverless, 数据库加速。

Serverless 0 次安装 0 次浏览 更新于 3/8/2026

name: cloudflare-hyperdrive description: Cloudflare Hyperdrive 用于连接 Workers 到数据库,提供连接池和缓存。适用于 PostgreSQL/MySQL、Drizzle/Prisma,或遇到连接池错误、TLS 问题、连接拒绝时使用。

关键词:hyperdrive, cloudflare hyperdrive, workers hyperdrive, postgres workers, mysql workers, connection pooling, query caching, node-postgres, pg, postgres.js, mysql2, drizzle hyperdrive, prisma hyperdrive, workers rds, workers aurora, workers neon, workers supabase, database acceleration, hybrid architecture, cloudflare tunnel database, wrangler hyperdrive, hyperdrive bindings, local development hyperdrive license: MIT metadata: version: “2.0.0” last_verified: “2025-11-18” production_tested: true token_savings: “~58%” errors_prevented: 6 templates_included: 0 references_included: 1

Cloudflare Hyperdrive

状态: 生产就绪 ✅ | 最后验证: 2025-11-18


什么是 Hyperdrive?

连接 Workers 到现有 PostgreSQL/MySQL 数据库:

  • 全局连接池
  • 查询缓存
  • 降低延迟
  • 支持 node-postgres、postgres.js、mysql2

快速开始 (5 分钟)

1. 创建 Hyperdrive 配置

bunx wrangler hyperdrive create my-db \
  --connection-string="postgres://user:pass@host:5432/database"

保存 id

2. 配置绑定

{
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2024-09-23",
  "compatibility_flags": ["nodejs_compat"],  // 必需!
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "<ID_FROM_STEP_1>"
    }
  ]
}

3. 安装驱动

bun add pg  # 或 postgres,或 mysql2

4. 查询数据库

import { Client } from 'pg';

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

    const result = await client.query('SELECT * FROM users LIMIT 10');
    await client.end();

    return Response.json(result.rows);
  }
};

加载 references/setup-guide.md 获取完整指南。


关键规则

始终要做 ✅

  1. 启用 nodejs_compat 标志 (必需!)
  2. 使用 env.HYPERDRIVE.connectionString (不是原始数据库字符串)
  3. 查询后关闭连接
  4. 显式处理错误
  5. 使用连接池 (内置)
  6. 本地测试 使用 wrangler dev
  7. 监控查询性能
  8. 使用预编译语句
  9. 启用查询缓存 (自动)
  10. 安全连接字符串 (使用密钥)

绝不要做 ❌

  1. 绝不要跳过 nodejs_compat (驱动无法工作)
  2. 绝不要在 Workers 中使用原始数据库连接字符串
  3. 绝不要保持连接打开 (连接池耗尽)
  4. 绝不要跳过错误处理 (数据库可能失败)
  5. 绝不要在代码中硬编码凭据
  6. 绝不要超过连接限制
  7. 绝不要使用 eval/Function (在 Workers 中被阻止)
  8. 绝不要为生产数据库跳过 TLS
  9. 绝不要使用阻塞查询 (Worker 超时)
  10. 绝不要向用户暴露数据库错误

数据库驱动

PostgreSQL (node-postgres)

import { Client } from 'pg';

const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query('SELECT * FROM users');
await client.end();

PostgreSQL (postgres.js)

import postgres from 'postgres';

const sql = postgres(env.HYPERDRIVE.connectionString);
const users = await sql`SELECT * FROM users`;

MySQL

import mysql from 'mysql2/promise';

const connection = await mysql.createConnection(env.HYPERDRIVE.connectionString);
const [rows] = await connection.execute('SELECT * FROM users');
await connection.end();

与 Drizzle ORM 配合使用

import { drizzle } from 'drizzle-orm/node-postgres';
import { Client } from 'pg';

const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();

const db = drizzle(client);
const users = await db.select().from(usersTable);

await client.end();

常见使用场景

使用场景 1: 只读查询

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

    const users = await client.query('SELECT * FROM users WHERE active = true');
    await client.end();

    return Response.json(users.rows);
  }
};

使用场景 2: 参数化查询

const userId = new URL(request.url).searchParams.get('id');

const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();

const result = await client.query(
  'SELECT * FROM users WHERE id = $1',
  [userId]
);

await client.end();

使用场景 3: 事务

const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();

try {
  await client.query('BEGIN');
  await client.query('UPDATE accounts SET balance = balance - 100 WHERE id = $1', [1]);
  await client.query('UPDATE accounts SET balance = balance + 100 WHERE id = $1', [2]);
  await client.query('COMMIT');
} catch (e) {
  await client.query('ROLLBACK');
  throw e;
} finally {
  await client.end();
}

支持的数据库

PostgreSQL:

  • Amazon RDS
  • Amazon Aurora
  • Neon
  • Supabase
  • Railway
  • Render
  • DigitalOcean
  • 任何 PostgreSQL 11+

MySQL:

  • Amazon RDS
  • Amazon Aurora
  • PlanetScale
  • 任何 MySQL 5.7+

官方文档


捆绑资源

参考 (references/):

  • setup-guide.md - 完整设置指南 (创建配置、绑定、查询)
  • connection-pooling.md - 连接池配置和最佳实践
  • query-caching.md - 查询缓存策略和优化
  • drizzle-integration.md - Drizzle ORM 集成模式
  • prisma-integration.md - Prisma ORM 集成模式
  • supported-databases.md - 支持的 PostgreSQL 和 MySQL 提供商的完整列表
  • tls-ssl-setup.md - TLS/SSL 安全连接配置
  • troubleshooting.md - 常见问题和解决方案
  • wrangler-commands.md - Hyperdrive 的完整 wrangler CLI 命令

模板 (templates/):

  • postgres-basic.ts - 使用 node-postgres 的基本 PostgreSQL
  • postgres-js.ts - 使用 postgres.js 驱动的 PostgreSQL
  • postgres-pool.ts - 使用连接池的 PostgreSQL
  • mysql2-basic.ts - 使用 mysql2 驱动的 MySQL
  • drizzle-postgres.ts - 使用 Drizzle ORM 的 PostgreSQL
  • drizzle-mysql.ts - 使用 Drizzle ORM 的 MySQL
  • prisma-postgres.ts - 使用 Prisma ORM 的 PostgreSQL
  • local-dev-setup.sh - 本地开发设置脚本
  • wrangler-hyperdrive-config.jsonc - Wrangler 配置示例

有问题?遇到问题?

  1. 查看 references/setup-guide.md 获取完整设置
  2. 验证 nodejs_compat 标志已启用
  3. 确保使用 env.HYPERDRIVE.connectionString
  4. 检查连接是否正确关闭