如何Design and Implement Caching Strategies:Claude Code 实战指南
学习如何design and implement caching strategies:Claude Code 实战. 包含实用代码示例和分步指导。
缓存戦略の设计にClaude Code使用メリット
缓存は适当地设计しないと、古い数据の显示や内存の浪費につながります。Claude Code 应用の数据アクセスパターンを分析し、最適な缓存戦略を提案・实现可以。
Redis缓存の实现
> Redis使用...的缓存レイヤー实现。
> 缓存无效化、TTL管理、缓存アサイドパターンで。
// src/lib/cache.ts
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL!);
interface CacheOptions {
ttl?: number; // 秒単位
prefix?: string;
}
export class CacheService {
private defaultTTL = 300; // 5分
async get<T>(key: string, options?: CacheOptions): Promise<T | null> {
const fullKey = this.buildKey(key, options?.prefix);
const data = await redis.get(fullKey);
if (!data) return null;
try {
return JSON.parse(data) as T;
} catch {
return null;
}
}
async set<T>(key: string, value: T, options?: CacheOptions): Promise<void> {
const fullKey = this.buildKey(key, options?.prefix);
const ttl = options?.ttl ?? this.defaultTTL;
await redis.setex(fullKey, ttl, JSON.stringify(value));
}
async getOrSet<T>(
key: string,
fetcher: () => Promise<T>,
options?: CacheOptions
): Promise<T> {
const cached = await this.get<T>(key, options);
if (cached !== null) return cached;
const data = await fetcher();
await this.set(key, data, options);
return data;
}
async invalidate(key: string, prefix?: string): Promise<void> {
const fullKey = this.buildKey(key, prefix);
await redis.del(fullKey);
}
async invalidatePattern(pattern: string): Promise<void> {
const keys = await redis.keys(pattern);
if (keys.length > 0) {
await redis.del(...keys);
}
}
private buildKey(key: string, prefix?: string): string {
return prefix ? `${prefix}:${key}` : key;
}
}
export const cache = new CacheService();
缓存アサイドパターンの实现
// src/services/product-service.ts
import { cache } from '@/lib/cache';
import { prisma } from '@/lib/db';
export class ProductService {
async getProduct(id: string) {
return cache.getOrSet(
`product:${id}`,
() => prisma.product.findUnique({
where: { id },
include: { category: true, reviews: { take: 10 } },
}),
{ ttl: 600, prefix: 'products' }
);
}
async getPopularProducts(limit = 20) {
return cache.getOrSet(
`popular:${limit}`,
() => prisma.product.findMany({
orderBy: { salesCount: 'desc' },
take: limit,
include: { category: true },
}),
{ ttl: 300, prefix: 'products' }
);
}
async updateProduct(id: string, data: UpdateProductInput) {
const product = await prisma.product.update({
where: { id },
data,
});
// 関連缓存を无效化
await cache.invalidate(`product:${id}`, 'products');
await cache.invalidatePattern('products:popular:*');
return product;
}
}
HTTP 缓存头部の配置
// src/middleware.ts
import { NextResponse, NextRequest } from 'next/server';
export function middleware(req: NextRequest) {
const res = NextResponse.next();
const path = req.nextUrl.pathname;
// 静的アセット:長期缓存
if (path.match(/\.(js|css|png|jpg|svg|woff2)$/)) {
res.headers.set('Cache-Control', 'public, max-age=31536000, immutable');
}
// API:缓存なし
if (path.startsWith('/api/')) {
res.headers.set('Cache-Control', 'no-store');
}
// 页面:短期缓存 + ISR
if (!path.startsWith('/api/') && !path.match(/\.[a-z]+$/)) {
res.headers.set('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');
}
return res;
}
内存缓存(应用内)
小規模な数据にはイン内存缓存が有效です。
// src/lib/memory-cache.ts
interface CacheEntry<T> {
value: T;
expiresAt: number;
}
export class MemoryCache {
private store = new Map<string, CacheEntry<unknown>>();
private maxSize: number;
constructor(maxSize = 1000) {
this.maxSize = maxSize;
}
get<T>(key: string): T | null {
const entry = this.store.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
this.store.delete(key);
return null;
}
return entry.value as T;
}
set<T>(key: string, value: T, ttlMs: number): void {
// サイズ制限チェック
if (this.store.size >= this.maxSize) {
const firstKey = this.store.keys().next().value;
if (firstKey) this.store.delete(firstKey);
}
this.store.set(key, {
value,
expiresAt: Date.now() + ttlMs,
});
}
clear(): void {
this.store.clear();
}
}
// 配置値などの頻繁にアクセスされる数据に使用
export const configCache = new MemoryCache(100);
缓存戦略の選定指南
| 数据の種類 | 推奨缓存 | TTL目安 |
|---|---|---|
| 配置マスタ | 内存 + Redis | 1时间 |
| 用户プロフィール | Redis | 10分 |
| 商品列表 | Redis + CDN | 5分 |
| 会话情報 | Redis | 24时间 |
| 静的アセット | CDN | 1年 |
| API响应 | HTTP Cache | 1分 |
缓存の监控
// 缓存ヒット率の計測
export class CacheMetrics {
private hits = 0;
private misses = 0;
recordHit() { this.hits++; }
recordMiss() { this.misses++; }
getHitRate(): number {
const total = this.hits + this.misses;
return total === 0 ? 0 : this.hits / total;
}
getStats() {
return {
hits: this.hits,
misses: this.misses,
hitRate: `${(this.getHitRate() * 100).toFixed(1)}%`,
};
}
}
总结
借助 Claude Code,Redis缓存、HTTP缓存、内存缓存など多層的な缓存戦略を高效地设计・实现可以。缓存の设计方針をCLAUDE.mdに記述しておくと、项目全体で一貫した实现が得られます。性能改善の全体像は生産性を3倍にするTips也可以参考。
Claude Code 的详细信息请参阅Anthropic官方文档。Redis的详细信息请参阅Redis官方文档。
#Claude Code
#caching
#Redis
#performance
#design
Related Posts
Advanced
Advanced
Claude Code Hooks 完全指南:自动格式化、自动测试等实用配置
详解如何通过 Claude Code Hooks 实现自动格式化和自动测试。包含实际配置示例和真实使用场景。
Advanced
Advanced
Claude Code MCP Server 配置指南与实战用例
全面介绍 Claude Code 的 MCP Server 功能。从外部工具连接、服务器配置到真实集成案例,一文掌握 MCP 生态。
Advanced
Advanced
CLAUDE.md 编写完全指南:项目配置最佳实践
深入讲解如何编写高效的 CLAUDE.md 文件。学会向 Claude Code 传达你的技术栈、规范和项目结构,最大化输出质量。