跳转到内容
搜索文档

使用 R2 实现数据持久化

最后更新 查看 MarkdownAgent 设置

将对象存储桶挂载为本地文件系统路径,以便在沙箱生命周期之间持久保存数据。本教程使用 Cloudflare R2,但同样的方法适用于任何 S3 兼容提供商。

本教程展示如何持久化挂载在 /data 的外部数据目录。如果希望 /workspace 中的工作项目持久化,请参阅备份与恢复

预计完成时间: 20 分钟

你将构建的内容

一个 Worker:处理数据,将结果存储在挂载为本地目录的 R2 存储桶中,并演示即使沙箱被销毁并重新创建,数据仍然持久存在。

你将学到的关键概念

  • 将 R2 存储桶挂载为文件系统路径
  • 跨沙箱生命周期的自动数据持久化
  • 使用标准文件操作处理挂载的存储

前提条件

  1. 注册 Cloudflare 账户
  2. 安装 Node.js

Node.js 版本管理器

使用 Voltanvm 等 Node 版本管理器,以避免权限问题并切换 Node.js 版本。本指南后续将介绍的 Wrangler 需要 Node 版本 16.17.0 或更高。

你还需要:

1. 创建项目

npm create cloudflare@latest -- data-pipeline --template=cloudflare/sandbox-sdk/examples/minimal
cd data-pipeline

2. 配置 R2 绑定

wrangler.json 中添加 R2 存储桶绑定:

wrangler.jsonjson
{
  "name": "data-pipeline",
  "compatibility_date": "2025-11-09",
  "durable_objects": {
    "bindings": [
      { "name": "Sandbox", "class_name": "Sandbox" }
    ]
  },
  "r2_buckets": [
    {
      "binding": "DATA_BUCKET",
      "bucket_name": "my-data-bucket"
    }
  ]
}

my-data-bucket 替换为你的 R2 存储桶名称。请先在 Cloudflare 仪表板 中创建该存储桶。

3. 构建数据处理程序

src/index.ts 替换为挂载 R2 并处理数据的代码:

import { getSandbox } from "@cloudflare/sandbox";

export { Sandbox } from "@cloudflare/sandbox";

export default {
	async fetch(request, env) {
		const url = new URL(request.url);
		const sandbox = getSandbox(env.Sandbox, "data-processor");

		// Mount R2 bucket to /data directory
		await sandbox.mountBucket("my-data-bucket", "/data", {
			endpoint: "https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com",
		});

		if (url.pathname === "/process") {
			// Process data and save to mounted R2
			const result = await sandbox.exec("python", {
				args: [
					"-c",
					`
import json
import os
from datetime import datetime

# Read input (or create sample data)
data = [
    {'id': 1, 'value': 42},
    {'id': 2, 'value': 87},
    {'id': 3, 'value': 15}
]

# Process: calculate sum and average
total = sum(item['value'] for item in data)
avg = total / len(data)

# Save results to mounted R2 (/data is the mounted bucket)
result = {
    'timestamp': datetime.now().isoformat(),
    'total': total,
    'average': avg,
    'processed_count': len(data)
}

os.makedirs('/data/results', exist_ok=True)
with open('/data/results/latest.json', 'w') as f:
    json.dump(result, f, indent=2)

print(json.dumps(result))
				`,
				],
			});

			return Response.json({
				message: "Data processed and saved to R2",
				result: JSON.parse(result.stdout),
			});
		}

		if (url.pathname === "/results") {
			// Read results from mounted R2
			const result = await sandbox.exec("cat", {
				args: ["/data/results/latest.json"],
			});

			if (!result.success) {
				return Response.json(
					{ error: "No results found yet" },
					{ status: 404 },
				);
			}

			return Response.json({
				message: "Results retrieved from R2",
				data: JSON.parse(result.stdout),
			});
		}

		if (url.pathname === "/destroy") {
			// Destroy sandbox to demonstrate persistence
			await sandbox.destroy();
			return Response.json({
				message: "Sandbox destroyed. Data persists in R2!",
			});
		}

		return new Response(
			`
Data Pipeline with Persistent Storage

Endpoints:
- POST /process  - Process data and save to R2
- GET /results   - Retrieve results from R2
- POST /destroy  - Destroy sandbox (data survives!)

Try this flow:
1. POST /process  (processes and saves to R2)
2. POST /destroy  (destroys sandbox)
3. GET /results   (data still accessible from R2)
		`,
			{ headers: { "Content-Type": "text/plain" } },
		);
	},
};
import { getSandbox, type Sandbox } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

interface Env {
	Sandbox: DurableObjectNamespace<Sandbox>;
	DATA_BUCKET: R2Bucket;
}

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const url = new URL(request.url);
		const sandbox = getSandbox(env.Sandbox, 'data-processor');

		// Mount R2 bucket to /data directory
		await sandbox.mountBucket('my-data-bucket', '/data', {
			endpoint: 'https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com'
		});

		if (url.pathname === '/process') {
			// Process data and save to mounted R2
			const result = await sandbox.exec('python', {
				args: ['-c', `
import json
import os
from datetime import datetime

# Read input (or create sample data)
data = [
    {'id': 1, 'value': 42},
    {'id': 2, 'value': 87},
    {'id': 3, 'value': 15}
]

# Process: calculate sum and average
total = sum(item['value'] for item in data)
avg = total / len(data)

# Save results to mounted R2 (/data is the mounted bucket)
result = {
    'timestamp': datetime.now().isoformat(),
    'total': total,
    'average': avg,
    'processed_count': len(data)
}

os.makedirs('/data/results', exist_ok=True)
with open('/data/results/latest.json', 'w') as f:
    json.dump(result, f, indent=2)

print(json.dumps(result))
				`]
			});

			return Response.json({
				message: 'Data processed and saved to R2',
				result: JSON.parse(result.stdout)
			});
		}

		if (url.pathname === '/results') {
			// Read results from mounted R2
			const result = await sandbox.exec('cat', {
				args: ['/data/results/latest.json']
			});

			if (!result.success) {
				return Response.json({ error: 'No results found yet' }, { status: 404 });
			}

			return Response.json({
				message: 'Results retrieved from R2',
				data: JSON.parse(result.stdout)
			});
		}

		if (url.pathname === '/destroy') {
			// Destroy sandbox to demonstrate persistence
			await sandbox.destroy();
			return Response.json({ message: 'Sandbox destroyed. Data persists in R2!' });
		}

		return new Response(`
Data Pipeline with Persistent Storage

Endpoints:
- POST /process  - Process data and save to R2
- GET /results   - Retrieve results from R2
- POST /destroy  - Destroy sandbox (data survives!)

Try this flow:
1. POST /process  (processes and saves to R2)
2. POST /destroy  (destroys sandbox)
3. GET /results   (data still accessible from R2)
		`, { headers: { 'Content-Type': 'text/plain' } });
	}
};

4. 部署到生产环境

生成 R2 API 令牌:

  1. Cloudflare 仪表板 中前往 R2 > Overview(概览)
  2. 选择 Manage R2 API Tokens(管理 R2 API 令牌)
  3. 创建具有 Object Read & Write 权限的令牌
  4. 复制 Access Key ID(访问密钥 ID)Secret Access Key(秘密访问密钥)

将凭据设置为 Worker secrets:

npx wrangler secret put AWS_ACCESS_KEY_ID
# Paste your R2 Access Key ID

npx wrangler secret put AWS_SECRET_ACCESS_KEY
# Paste your R2 Secret Access Key

Worker secrets 经过加密,仅已部署的 Worker 可访问。调用 mountBucket() 时,SDK 会自动检测这些凭据。

部署你的 Worker:

npx wrangler deploy

部署后,wrangler 会输出你的 Worker URL(例如 https://data-pipeline.yourname.workers.dev)。

5. 测试持久化流程

现在针对已部署的 Worker 进行测试。将 YOUR_WORKER_URL 替换为你的实际 Worker URL:

# 1. Process data (saves to R2)
curl -X POST https://YOUR_WORKER_URL/process
# Returns: { "message": "Data processed...", "result": { "total": 144, "average": 48, ... } }

# 2. Verify data is accessible
curl https://YOUR_WORKER_URL/results
# Returns the same results from R2

# 3. Destroy the sandbox
curl -X POST https://YOUR_WORKER_URL/destroy
# Returns: { "message": "Sandbox destroyed. Data persists in R2!" }

# 4. Access results again (from new sandbox)
curl https://YOUR_WORKER_URL/results
# Still works! Data persisted across sandbox lifecycle

关键洞察:销毁沙箱后,下一次请求会创建新的沙箱实例,挂载同一个 R2 存储桶,并发现数据仍然存在。

你学到了什么

在本教程中,你构建了一个通过 R2 存储桶挂载演示文件系统持久化的数据处理流水线:

  • 挂载存储桶:使用 mountBucket() 将 R2 作为本地目录访问
  • 标准文件操作:使用熟悉的文件系统命令(cat、Python open() 等)访问挂载的存储桶
  • 自动持久化:写入挂载目录的数据在沙箱销毁后仍然保留
  • 选择正确的持久化模型:对 /data 等外部存储目录使用存储桶挂载;当你需要 /workspace 下的持久工作区时,考虑备份与恢复
  • 凭据管理:使用环境变量或显式凭据配置 R2 访问

后续步骤

相关资源

这篇文档对您有帮助吗?