关于 caching-cdn-strategy-planner
用于规划客户端、CDN、服务器和数据库各层缓存的 Skill,涵盖 CDN 配置、基于 Redis 的服务端缓存、失效策略、缓存头和监控。
主要功能
- 01分层缓存规划
- 02CloudFront 配置示例
- 03Redis 服务端缓存
- 04缓存失效策略
- 05缓存头设置
- 06监控检查清单
适用场景
- 01规划应用的缓存层
- 02为服务器请求添加 Redis 缓存
- 03定义数据更新后的缓存失效方式
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ patricio0312rev/ skills --skill caching-cdn-strategy-planner安装后在 Claude Code 中输入/caching-cdn-strategy-planner确认已加载。
详细介绍
缓存与 CDN 策略规划
在各层设计有效的缓存策略。
缓存层级
Client → CDN (Edge) → Server Cache → Database
CDN 配置(CloudFront)
const distribution = {
Origins: [
{
DomainName: "api.example.com",
CustomHeaders: [
{
HeaderName: "X-CDN-Secret",
HeaderValue: process.env.CDN_SECRET,
},
],
},
],
DefaultCacheBehavior: {
ViewerProtocolPolicy: "redirect-to-https",
AllowedMethods: ["GET", "HEAD", "OPTIONS"],
CachedMethods: ["GET", "HEAD"],
Compress: true,
DefaultTTL: 86400, // 1 day
MaxTTL: 31536000, // 1 year
MinTTL: 0,
ForwardedValues: {
QueryString: true,
Cookies: { Forward: "none" },
Headers: ["Accept", "Accept-Encoding"],
},
},
CacheBehaviors: [
{
PathPattern: "/api/static/*",
DefaultTTL: 31536000, // 1 year - never changes
},
{
PathPattern: "/api/dynamic/*",
DefaultTTL: 300, // 5 min - changes frequently
},
],
};
服务端缓存(Redis)
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
async function getCachedOrFetch<T>(
key: string,
fetcher: () => Promise<T>,
ttl: number = 3600
): Promise<T> {
// Try cache
const cached = await redis.get(key);
if (cached) {
return JSON.parse(cached);
}
// Fetch and cache
const data = await fetcher();
await redis.setex(key, ttl, JSON.stringify(data));
return data;
}
// Usage
app.get('/api/user/:id', async (req, res) => {
const user = await getCachedOrFetch(
\`user:\${req.params.id}\`,
() => prisma.user.findUnique({ where: { id: req.params.id } }),
3600
);
res.json(user);
});
缓存失效
// Invalidate on update
app.put('/api/user/:id', async (req, res) => {
const user = await prisma.user.update({
where: { id: req.params.id },
data: req.body,
});
// Invalidate cache
await redis.del(\`user:\${req.params.id}\`);
// Invalidate CDN
await cloudfront.createInvalidation({
DistributionId: DISTRIBUTION_ID,
InvalidationBatch: {
Paths: { Items: [\`/api/user/\${req.params.id}\`] },
CallerReference: Date.now().toString(),
},
});
res.json(user);
});
缓存标头
app.get("/api/products", (req, res) => {
res.set({
"Cache-Control": "public, max-age=3600", // Browser + CDN: 1h
ETag: generateETag(products),
"Last-Modified": new Date(products.updatedAt).toUTCString(),
});
res.json(products);
});
app.get("/api/user/profile", (req, res) => {
res.set({
"Cache-Control": "private, no-cache", // No caching (sensitive)
});
res.json(profile);
});
输出检查清单
- 已配置 CDN
- 已实现服务端缓存
- 已制定失效策略
- 已设置缓存标头
- 已配置监控 ENDFILE
评论
支持 Markdown