redis-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRedis Expert
Redis专家
Installation
安装
bash
undefinedbash
undefinedUbuntu
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
undefineddocker run -d --name redis -p 6379:6379 redis:alpine
undefinedBasic Commands
基础命令
bash
redis-clibash
redis-cliStrings
字符串类型
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
undefinedZADD leaderboard 100 "player1"
ZRANGE leaderboard 0 -1 WITHSCORES
undefinedNode.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
缓存策略
| Strategy | Use Case | Implementation |
|---|---|---|
| Cache-Aside | Read-heavy | Check cache → Miss → Load DB → Store cache |
| Write-Through | Consistency | Write DB → Write cache |
| Write-Behind | Write-heavy | Write cache → Async write DB |
| TTL | General | Set 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!');