用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tools-only/X-Skills --skill implement-caching命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
基于 SOC 职业分类
正在显示 SKILL.md
| name | implement-caching |
| description | Implement comprehensive multi-level API caching strategies with Redis, CDN,... |
| shortcut | cach |
| category | api |
| difficulty | intermediate |
| estimated_time | 2-3 hours |
| version | 2.0.0 |
Creates comprehensive multi-level caching strategies to dramatically improve API performance, reduce database load, and enhance user experience. Implements Redis for server-side caching, CDN integration for edge caching, and proper HTTP cache headers for client-side optimization.
Use this command when:
Do NOT use this command for:
Before running this command, ensure:
The command examines your API to determine optimal caching strategies:
Sets up Redis-based caching with intelligent patterns:
Implements proper HTTP caching directives:
Configures edge caching for global distribution:
Creates sophisticated invalidation strategies:
The command generates a complete caching implementation:
api-caching/
├── src/
│ ├── cache/
│ │ ├── redis-client.js
│ │ ├── cache-middleware.js
│ │ ├── cache-strategies.js
│ │ └── invalidation-service.js
│ ├── middleware/
│ │ ├── http-cache-headers.js
│ │ └── cdn-integration.js
│ └── utils/
│ ├── cache-key-generator.js
│ └── cache-metrics.js
├── config/
│ ├── cache-config.json
│ ├── redis.config.js
│ └── cdn-rules.json
├── tests/
│ └── cache.test.js
└── docs/
└── caching-strategy.md
Scenario: High-traffic product catalog requiring sub-100ms response times
Generated Redis Implementation:
// cache/redis-client.js
import Redis from 'ioredis';
import { promisify } from 'util';
class CacheManager {
constructor() {
this.client = new Redis({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASSWORD,
retryStrategy: (times) => Math.min(times * 50, 2000),
enableOfflineQueue: false
});
this.defaultTTL = 3600; // 1 hour default
this.client.on('error', this.handleError);
}
async get(key, options = {}) {
try {
const cached = await this.client.get(key);
(cached) {
..(key);
.(cached);
}
..(key);
(options.) {
data = options.();
.(key, data, options.);
data;
}
;
} (error) {
.(error);
options. ? options.() : ;
}
}
() {
serialized = .(value);
(ttl) {
..(key, ttl, serialized);
} {
..(key, serialized);
}
(value.) {
( tag value.) {
..(, key);
}
}
}
() {
keys = ..();
(keys. > ) {
..(...keys);
..();
}
keys.;
}
() {
keys = ..(pattern);
(keys. > ) {
..(...keys);
}
keys.;
}
}
= () => {
(req, res, next) => {
(req. !== ) {
();
}
cacheKey = (req);
cached = cacheManager.(cacheKey);
(cached) {
res.(, );
res.(, cacheKey);
res.(cached);
}
originalSend = res.;
res. = () {
res. = originalSend;
(res. === ) {
cacheManager.(cacheKey, data, options.);
}
res.(, );
res.(, cacheKey);
res.(data);
};
();
};
};
app.(,
({ : }),
(req, res) => {
product = db.(req..);
res.(product);
}
);
Scenario: Global content delivery with CloudFlare integration
Generated CDN Configuration:
// cdn-integration.js
class CDNManager {
constructor(config) {
this.zoneId = config.cloudflareZoneId;
this.apiToken = config.cloudflareApiToken;
this.baseUrl = 'https://api.cloudflare.com/client/v4';
}
// Set CDN cache headers
setCacheHeaders(res, options = {}) {
const {
maxAge = 3600,
sMaxAge = 86400,
staleWhileRevalidate = 60,
staleIfError = 3600,
mustRevalidate = false,
public = true
} = options;
// Browser cache
let cacheControl = public ? 'public' : 'private';
cacheControl += `, max-age=${maxAge}`;
// CDN cache (s-maxage)
cacheControl += `, s-maxage=${sMaxAge}`;
// Stale content serving
if (staleWhileRevalidate) {
cacheControl += `, stale-while-revalidate=${staleWhileRevalidate}`;
}
if (staleIfError) {
cacheControl += `, stale-if-error=${staleIfError}`;
}
if (mustRevalidate) {
cacheControl += ', must-revalidate';
}
res.set('Cache-Control', cacheControl);
res.(, options.?.() || );
res.(, );
}
() {
{ urls, tags, everything = } = options;
purgeBody = {};
(everything) {
purgeBody. = ;
} (tags) {
purgeBody. = tags;
} (urls) {
purgeBody. = urls;
}
response = (
,
{
: ,
: {
: ,
:
},
: .(purgeBody)
}
);
response.();
}
}
app.(, (req, res) => {
content = cms.(req..);
cdnManager.(res, {
: ,
: ,
: [, ]
});
res.(content);
});
app.(, (req, res) => {
content = cms.(req.., req.);
cdnManager.({
: []
});
cacheManager.();
res.({ : });
});
Scenario: Critical data that must always be cached for performance
Generated Cache Warming Strategy:
// cache-warming-service.js
class CacheWarmer {
constructor(cacheManager, dataSource) {
this.cache = cacheManager;
this.dataSource = dataSource;
this.warmingInterval = 5 * 60 * 1000; // 5 minutes
}
async warmCache() {
console.log('Starting cache warming...');
// Warm frequently accessed data
const criticalData = [
{ key: 'homepage:featured', fetch: () => this.dataSource.getFeaturedProducts() },
{ key: 'categories:all', fetch: () => this.dataSource.getAllCategories() },
{ key: 'config:site', fetch: () => this.dataSource.getSiteConfig() }
];
const warmingPromises = criticalData.map(async ({ key, fetch }) => {
try {
const data = ();
..(key, data, );
{ key, : };
} (error) {
{ key, : , : error. };
}
});
results = .(warmingPromises);
.(, results);
results;
}
() {
.();
( {
.();
}, .);
}
}
Symptoms: Cache operations timeout or fail Cause: Redis server unavailable or misconfigured Solution:
// Implement fallback to direct database access
if (!redis.isReady()) {
console.warn('Cache unavailable, falling back to database');
return await database.query(sql);
}
Prevention: Implement circuit breaker pattern and health checks
Symptoms: Multiple simultaneous cache misses cause database overload Cause: Popular item expires, causing many requests to rebuild cache Solution: Implement probabilistic early expiration or distributed locks
Symptoms: Users see outdated information Cause: Cache TTL too long or invalidation not triggered Solution: Implement event-based invalidation and reduce TTL values
--ttl/cache --ttl 7200--strategycache-aside, write-through, write-behindcache-aside/cache --strategy write-through--cdncloudflare, fastly, cloudfront, akamaicloudflare/cache --cdn fastly✅ DO:
❌ DON'T:
💡 TIPS:
/api-rate-limiter - Implement rate limiting with Redis/api-response-validator - Validate cached responses/api-monitoring-dashboard - Monitor cache performance/api-load-tester - Test cache effectiveness under load⚠️ Security Considerations:
Solution: Review cache key strategy and TTL values
Solution: Implement LRU eviction policy and reduce object sizes
Solution: Verify tag associations and event triggers
Last updated: 2025-10-11 Quality score: 9.5/10 Tested with: Redis 7.0, CloudFlare, Fastly, AWS CloudFront