[ PROMPT_NODE_24026 ]
Cache Reserve API 参考
[ SKILL_DOCUMENTATION ]
# Cache Reserve API
## 智能体 (Workers) 集成
┌────────────────────────────────────────────────────────────────┐
│ 关键提示:Workers Cache API ≠ Cache Reserve │
│ │
│ • Workers caches.default / cache.put() → 仅限边缘缓存 │
│ • Cache Reserve → 区域级设置,自动运行,无单请求 API │
│ • 你不能从 Workers 选择性地写入 Cache Reserve │
│ • Cache Reserve 适用于标准 fetch(),而非 cache.put() │
└────────────────────────────────────────────────────────────────┘
Cache Reserve 是**区域级配置**,而非单请求 API。一旦为该区域启用,它将自动运行:
### 标准 Fetch (推荐)
typescript
// Cache Reserve 通过标准 fetch 自动工作
export default {
async fetch(request: Request, env: Env): Promise {
// 标准 fetch 会自动使用 Cache Reserve
return await fetch(request);
}
};
### Cache API 限制
**重要**:`cache.put()` 与 Cache Reserve 或分层缓存**不兼容**。
typescript
// ❌ 错误:cache.put() 会绕过 Cache Reserve
const cache = caches.default;
let response = await cache.match(request);
if (!response) {
response = await fetch(request);
await cache.put(request, response.clone()); // 绕过了 Cache Reserve!
}
// ✅ 正确:使用标准 fetch 以兼容 Cache Reserve
return await fetch(request);
// ✅ 正确:仅对自定义缓存命名空间使用 Cache API
const customCache = await caches.open('my-custom-cache');
let response = await customCache.match(request);
if (!response) {
response = await fetch(request);
await customCache.put(request, response.clone()); // 自定义缓存没问题
}
## 清除与缓存管理
### 按 URL 清除 (即时)
typescript
// 立即从 Cache Reserve 中清除特定 URL
const purgeCacheReserveByURL = async (
zoneId: string,
apiToken: string,
urls: string[]
) => {
const response = await fetch(
`https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ files: urls })
}
);
return await response.json();
};
// 示例用法
await purgeCacheReserveByURL('zone123', 'token456', [
'https://example.com/image.jpg',
'https://example.com/video.mp4'
]);
### 按标签/主机清除