跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

Hyperdrive(Postgres 与 MySQL)

最后更新 查看 MarkdownAgent 设置

将现有区域数据库转变为全球分布式数据库。

Free 和 Paid 套餐均可用

Hyperdrive 是一项加速对现有数据库查询的服务,使你能从全球任意位置通过 Cloudflare Workers 更快访问数据,无论用户位于何处。

Hyperdrive 支持任何 PostgreSQL 或 MySQL 数据库,包括托管在 AWS、Google Cloud、Azure、Supabase、Neon 和 PlanetScale 上的数据库。Hyperdrive 也支持 CockroachDB 和 Timescale 等兼容 PostgreSQL 的数据库。 你无需编写新代码或替换常用工具:Hyperdrive 可与你现有的代码和工具配合使用。

在 Cloudflare Workers 应用中使用 Hyperdrive 的连接详情,配合现有数据库驱动和对象关系映射(ORM)库。

示例

PostgreSQL

import { Client } from "pg";

export default {
    async fetch(request, env, ctx): 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();
            // Sample SQL query
            const result = await client.query("SELECT * FROM pg_tables");

            return Response.json(result.rows);
        } catch (e) {
            return Response.json({ error: e instanceof Error ? e.message : e }, { status: 500 });
        }
    },
} satisfies ExportedHandler<{ HYPERDRIVE: Hyperdrive }>;
    {
        "$schema": "node_modules/wrangler/config-schema.json",
        "name": "WORKER-NAME",
        "main": "src/index.ts",
        "upload_source_maps": true,
        "compatibility_date": "2025-02-04",
        "compatibility_flags": [
            "nodejs_compat"
        ],
        "observability": {
            "enabled": true
        },
        "hyperdrive": [
            {
                "binding": "HYPERDRIVE",
                "id": "<YOUR_HYPERDRIVE_ID>",
                "localConnectionString": "<ENTER_LOCAL_CONNECTION_STRING_FOR_LOCAL_DEVELOPMENT_HERE>"
            }
        ]
    }

MySQL

import { createConnection } from 'mysql2/promise';

export default {
  async fetch(request, env, ctx): Promise<Response> {
    // Create a new connection on each request. Hyperdrive maintains the
    // underlying database connection pool, so creating a new client is fast.
    const connection = await createConnection({
         host: env.HYPERDRIVE.host,
         user: env.HYPERDRIVE.user,
         password: env.HYPERDRIVE.password,
         database: env.HYPERDRIVE.database,
         port: env.HYPERDRIVE.port,

     // This is needed to use mysql2 with Workers
     // This configures mysql2 to use static parsing instead of eval() parsing (not available on Workers)
     disableEval: true
  });

  const [results, fields] = await connection.query('SHOW tables;');

  return new Response(JSON.stringify({ results, fields }), {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '\*',
    },
  });
}} satisfies ExportedHandler<{ HYPERDRIVE: Hyperdrive }>;
    {
        "$schema": "node_modules/wrangler/config-schema.json",
        "name": "WORKER-NAME",
        "main": "src/index.ts",
        "upload_source_maps": true,
        "compatibility_date": "2025-02-04",
        "compatibility_flags": [
            "nodejs_compat"
        ],
        "observability": {
            "enabled": true
        },
        "hyperdrive": [
            {
                "binding": "HYPERDRIVE",
                "id": "<YOUR_HYPERDRIVE_ID>",
                "localConnectionString": "<ENTER_LOCAL_CONNECTION_STRING_FOR_LOCAL_DEVELOPMENT_HERE>"
            }
        ]
    }
快速入门

功能

连接数据库

将 Hyperdrive 连接到现有数据库,并部署查询该数据库的 Worker。

PostgreSQL 支持

Hyperdrive 可连接任何 PostgreSQL 或 PostgreSQL 兼容数据库。

MySQL 支持

Hyperdrive 可连接任何 MySQL 数据库。

查询缓存

对数据库上最常执行的查询默认启用缓存。


相关产品

Workers

构建无服务器应用,在全球即时部署,获得卓越的性能、可靠性和规模。

Pages

快速部署动态前端应用。


更多资源

定价

了解 Hyperdrive 定价。

限制

了解 Hyperdrive 限制。

存储选项

了解更多可在 Workers 上构建的存储和数据库选项。

开发者 Discord

在 Discord 上与 Workers 社区交流,提问、展示你的项目并与其他开发者讨论平台。

@CloudflareDev

关注 Twitter 上的 @CloudflareDev,了解产品公告和 Cloudflare 开发者平台新动态。

这篇文档对您有帮助吗?