redis-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Redis Expert

Redis专家

Installation

安装

bash
undefined
bash
undefined

Ubuntu

Ubuntu

apt install redis-server -y systemctl enable redis-server
apt install redis-server -y systemctl enable redis-server

Docker

Docker

docker run -d --name redis -p 6379:6379 redis:alpine
undefined
docker run -d --name redis -p 6379:6379 redis:alpine
undefined

Basic Commands

基础命令

bash
redis-cli
bash
redis-cli

Strings

字符串类型

SET key "value" GET key SETEX key 3600 "value" # With TTL (1 hour) TTL key # Check TTL
SET key "value" GET key SETEX key 3600 "value" # 设置TTL(1小时) TTL key # 查看TTL

Hash (objects)

哈希(对象)

HSET user:1 name "John" email "john@example.com" HGET user:1 name HGETALL user:1
HSET user:1 name "John" email "john@example.com" HGET user:1 name HGETALL user:1

Lists

列表

LPUSH queue "task1" RPOP queue
LPUSH queue "task1" RPOP queue

Sets

集合

SADD tags "node" "redis" SMEMBERS tags
SADD tags "node" "redis" SMEMBERS tags

Sorted Sets

有序集合

ZADD leaderboard 100 "player1" ZRANGE leaderboard 0 -1 WITHSCORES
undefined
ZADD leaderboard 100 "player1" ZRANGE leaderboard 0 -1 WITHSCORES
undefined

Node.js Integration

Node.js集成

typescript
import { createClient } from 'redis';

const redis = createClient({ url: 'redis://localhost:6379' });
await redis.connect();

// Cache pattern
async function getUser(id: string) {
  const cached = await redis.get(`user:${id}`);
  if (cached) return JSON.parse(cached);
  
  const user = await db.user.findUnique({ where: { id } });
  await redis.setEx(`user:${id}`, 3600, JSON.stringify(user));
  return user;
}

// Invalidate
await redis.del(`user:${id}`);
typescript
import { createClient } from 'redis';

const redis = createClient({ url: 'redis://localhost:6379' });
await redis.connect();

// 缓存模式
async function getUser(id: string) {
  const cached = await redis.get(`user:${id}`);
  if (cached) return JSON.parse(cached);
  
  const user = await db.user.findUnique({ where: { id } });
  await redis.setEx(`user:${id}`, 3600, JSON.stringify(user));
  return user;
}

// 缓存失效
await redis.del(`user:${id}`);

Caching Strategies

缓存策略

StrategyUse CaseImplementation
Cache-AsideRead-heavyCheck cache → Miss → Load DB → Store cache
Write-ThroughConsistencyWrite DB → Write cache
Write-BehindWrite-heavyWrite cache → Async write DB
TTLGeneralSet expiration time
策略适用场景实现方式
Cache-Aside(旁路缓存)读密集型检查缓存 → 未命中 → 读取数据库 → 存入缓存
Write-Through(写穿透)强一致性要求写入数据库 → 写入缓存
Write-Behind(写回)写密集型写入缓存 → 异步写入数据库
TTL(过期时间)通用场景设置过期时间

Common Patterns

常见模式

typescript
// Rate limiting
async function rateLimit(ip: string, limit = 100) {
  const key = `rate:${ip}`;
  const count = await redis.incr(key);
  if (count === 1) await redis.expire(key, 60);
  return count <= limit;
}

// Session storage
app.use(session({
  store: new RedisStore({ client: redis }),
  secret: 'secret',
  resave: false,
  saveUninitialized: false
}));

// Pub/Sub
await redis.subscribe('channel', (message) => {
  console.log('Received:', message);
});
await redis.publish('channel', 'Hello!');
typescript
// 限流
async function rateLimit(ip: string, limit = 100) {
  const key = `rate:${ip}`;
  const count = await redis.incr(key);
  if (count === 1) await redis.expire(key, 60);
  return count <= limit;
}

// 会话存储
app.use(session({
  store: new RedisStore({ client: redis }),
  secret: 'secret',
  resave: false,
  saveUninitialized: false
}));

// 发布/订阅
await redis.subscribe('channel', (message) => {
  console.log('Received:', message);
});
await redis.publish('channel', 'Hello!');