Claude Code के साथ Redis
Claude Code का उपयोग करके redis सीखें। Practical tips और code examples शामिल हैं।
Redis cacheのimportant性
Redisはインメモリdataストア के रूप में、cache、セッションmanagement、リアルタイムprocessingに広く使われてい है।Claude Code का उपयोग करके、appropriateなcache戦略を設計しefficientlyimplementationでき है।
basic cache層
import { Redis } from "ioredis";
const redis = new Redis(process.env.REDIS_URL!);
class CacheService {
private redis: Redis;
private defaultTTL: number;
constructor(redis: Redis, defaultTTL = 300) {
this.redis = redis;
this.defaultTTL = defaultTTL;
}
async get<T>(key: string): Promise<T | null> {
const data = await this.redis.get(key);
if (!data) return null;
try {
return JSON.parse(data) as T;
} catch {
return null;
}
}
async set<T>(key: string, value: T, ttl?: number): Promise<void> {
const serialized = JSON.stringify(value);
await this.redis.set(key, serialized, "EX", ttl ?? this.defaultTTL);
}
async delete(key: string): Promise<void> {
await this.redis.del(key);
}
async deletePattern(pattern: string): Promise<void> {
const keys = await this.redis.keys(pattern);
if (keys.length > 0) {
await this.redis.del(...keys);
}
}
}
const cache = new CacheService(redis);
Cache-Aside pattern
async function getPostById(id: string): Promise<Post | null> {
const cacheKey = `post:${id}`;
// 1. cache सेfetch
const cached = await cache.get<Post>(cacheKey);
if (cached) {
return cached;
}
// 2. DB सेfetch
const post = await prisma.post.findUnique({
where: { id },
include: { author: true, categories: true },
});
if (!post) return null;
// 3. cacheに保存(5分)
await cache.set(cacheKey, post, 300);
return post;
}
// update時のcache無効化
async function updatePost(id: string, data: Partial<Post>) {
const updated = await prisma.post.update({
where: { id },
data,
});
// 関連するcacheを無効化
await cache.delete(`post:${id}`);
await cache.deletePattern("posts:list:*");
return updated;
}
list結果のcache
async function getPostsList(params: {
page: number;
category?: string;
}): Promise<PaginatedResult<Post>> {
const cacheKey = `posts:list:${params.page}:${params.category || "all"}`;
const cached = await cache.get<PaginatedResult<Post>>(cacheKey);
if (cached) return cached;
const result = await fetchPostsFromDB(params);
// list結果は短めのTTL(1分)
await cache.set(cacheKey, result, 60);
return result;
}
cachedecorator
function Cacheable(ttl: number = 300) {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
const cacheKey = `${target.constructor.name}:${propertyKey}:${JSON.stringify(args)}`;
const cached = await cache.get(cacheKey);
if (cached) return cached;
const result = await originalMethod.apply(this, args);
await cache.set(cacheKey, result, ttl);
return result;
};
return descriptor;
};
}
class PostService {
@Cacheable(300)
async getById(id: string) {
return prisma.post.findUnique({ where: { id } });
}
@Cacheable(60)
async getPopular(limit: number = 10) {
return prisma.post.findMany({
where: { published: true },
orderBy: { viewCount: "desc" },
take: limit,
});
}
}
セッションmanagement
import session from "express-session";
import RedisStore from "connect-redis";
const redisStore = new RedisStore({
client: redis,
prefix: "sess:",
ttl: 86400, // 24時बीच
});
app.use(
session({
store: redisStore,
secret: process.env.SESSION_SECRET!,
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === "production",
httpOnly: true,
maxAge: 86400 * 1000,
sameSite: "strict",
},
})
);
レート制限
async function rateLimiter(
key: string,
maxRequests: number,
windowSeconds: number
): Promise<{ allowed: boolean; remaining: number; resetAt: number }> {
const now = Math.floor(Date.now() / 1000);
const windowKey = `ratelimit:${key}:${Math.floor(now / windowSeconds)}`;
const current = await redis.incr(windowKey);
if (current === 1) {
await redis.expire(windowKey, windowSeconds);
}
const remaining = Math.max(0, maxRequests - current);
const resetAt = (Math.floor(now / windowSeconds) + 1) * windowSeconds;
return {
allowed: current <= maxRequests,
remaining,
resetAt,
};
}
// middleware के रूप में使用
async function rateLimitMiddleware(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
const key = req.ip || "unknown";
const result = await rateLimiter(key, 100, 60);
res.set("X-RateLimit-Remaining", String(result.remaining));
res.set("X-RateLimit-Reset", String(result.resetAt));
if (!result.allowed) {
return res.status(429).json({ error: "Too many requests" });
}
next();
}
Claude Code सेのutilization
RediscacheのimplementationをClaude Code को requestする例 है।エッジでのcacheके बारे मेंはエッジコンピューティング、asyncprocessingはjobqueue・asyncprocessingもदेखें。
Rediscache層を設計して。
- Cache-Asidepatternでの読み取りcache
- update時のcache無効化戦略
- APIレート制限
- セッションmanagement
- cacheのヒット率monitoring
Redisके details के लिएRedisofficial documentationをदेखें。Claude Codeのuse करने का तरीकाはofficial documentationでconfirmでき है।
Summary
Rediscacheはapplicationのperformanceを劇的に向ऊपरさせ है।Claude Code का उपयोग करके、cache戦略の設計 से無効化patternのimplementation तक、一貫したcache層 build किया जा सकता है。
Related Posts
Claude Code Hooks में Mastery: Auto-Format, Auto-Test, और बहुत कुछ
Claude Code hooks से auto-formatting और auto-testing setup करना सीखें। Practical configuration examples और real-world use cases शामिल हैं।
Claude Code MCP Server Setup और Practical Use Cases
Claude Code की MCP server capabilities की comprehensive guide। External tools connect करना, servers configure करना, और real-world integration examples सीखें।
CLAUDE.md लिखने की Complete Guide: Project Configuration की Best Practices
Effective CLAUDE.md files लिखने की thorough guide। अपना tech stack, conventions, और project structure communicate करना सीखें और Claude Code की output quality maximize करें।