Redis 作為高效能記憶體資料庫,是 Node.js 微服務、快取、Session、排行榜、分散式鎖的首選。本文以 node-redis (v4+) 為例,涵蓋連線管理、CRUD、過期策略、發布訂閱、Pipeline、Cluster 模式與生產環境最佳實踐。
npm install redis@4 # v4+ 原生 Promise、Cluster、TypeScript 支援
const { createClient } = require('redis');
const client = createClient({
socket: { host: '127.0.0.1', port: 6379 },
// password: 'your-password',
// database: 0
});
client.on('error', (err) => console.error('Redis Client Error', err));
client.on('connect', () => console.log('Redis 連線中...'));
client.on('ready', () => console.log('Redis 就緒可用'));
client.on('end', () => console.log('Redis 連線關閉'));
await client.connect(); // v4 必須 await connect()
// === String 基本操作 ===
await client.set('string:key', 'Hello World');
const val = await client.get('string:key');
console.log(val); // 'Hello World'
// 設定過期時間 (EX = 秒, PX = 毫秒, EXAT/ PXAT = UNIX 時間戳)
await client.set('temp:key', 'expire in 10s', { EX: 10 });
await client.set('temp:ms', 'expire in 500ms', { PX: 500 });
// 原子性設定不存在才設定 (NX)
await client.set('lock:key', '1', { NX: true, EX: 5 }); // 分散式鎖雛形
// 批次操作
await client.mSet({ 'k1': 'v1', 'k2': 'v2' });
const vals = await client.mGet(['k1', 'k2']); // ['v1', 'v2']
// 設定/更新過期時間
await client.expire('string:key', 30); // 30 秒後過期
await client.pexpire('string:key', 30000); // 毫秒精度
await client.expireAt('string:key', Math.floor(Date.now()/1000) + 60); // 指定 UNIX 時間戳
// 查詢剩餘 TTL
const ttlSec = await client.ttl('string:key'); // 秒,-2=不存在, -1=無過期
const ttlMs = await client.pttl('string:key'); // 毫秒
// 移除過期設定(變永久)
await client.persist('string:key');
async function demoTTL() {
await client.set('demo:key', 'Hello Redis', { EX: 5 });
const timer = setInterval(async () => {
const [val, ttl] = await Promise.all([
client.get('demo:key'),
client.ttl('demo:key')
]);
if (val) {
console.log(`值: ${val}, 剩餘: ${ttl}s`);
} else {
clearInterval(timer);
console.log('Key 已過期');
await client.quit();
}
}, 1000);
}
demoTTL();
// Hash (物件/實體儲存)
await client.hSet('user:1001', { name: 'Alice', age: '28', role: 'admin' });
const user = await client.hGetAll('user:1001'); // { name: 'Alice', age: '28', ... }
await client.hIncrBy('user:1001', 'age', 1); // 原子遞增
// List (佇列/棧)
await client.lPush('queue:tasks', 'task1', 'task2');
const task = await client.rPop('queue:tasks'); // 阻塞版: bRPop
// Set (去重/標籤/共同好友)
await client.sAdd('tags:article:1', 'tech', 'nodejs', 'redis');
const tags = await client.sMembers('tags:article:1');
const common = await client.sInter('tags:article:1', 'tags:article:2');
// Sorted Set (排行榜/延遲隊列/速率限制)
await client.zAdd('leaderboard', { score: 100, value: 'player1' });
await client.zIncrBy('leaderboard', 10, 'player1');
const top10 = await client.zRange('leaderboard', 0, 9, { REV: true }); // 高分在前
const pipeline = client.multi();
for (let i = 0; i < 1000; i++) {
pipeline.set(`batch:key:${i}`, `value${i}`);
pipeline.expire(`batch:key:${i}`, 3600);
}
const results = await pipeline.exec(); // 原子性執行,單次網路往返
console.log('執行結果數:', results.length);
// 單機多核:建立多個連線物件(node-redis v4 內建連線池概念較弱,建議自行管理池或用 ioredis)
// 正式生產強烈推薦 ioredis(功能更完整、Cluster 原生支援、連線池內建)
// npm install ioredis
const Redis = require('ioredis');
const cluster = new Redis.Cluster([
{ host: '10.0.0.1', port: 7000 },
{ host: '10.0.0.2', port: 7000 },
{ host: '10.0.0.3', port: 7000 }
], {
maxRedirections: 3,
retryStrategy: (times) => Math.min(times * 50, 2000),
enableOfflineQueue: true
});
// 應用啟動時建立單例
let redisClient;
async function getRedis() {
if (!redisClient) {
redisClient = createClient({ /* config */ });
redisClient.on('error', err => logger.error('Redis error', err));
await redisClient.connect();
}
return redisClient;
}
// 應用關閉時優雅關閉
process.on('SIGTERM', async () => {
if (redisClient) await redisClient.quit();
process.exit(0);
});
business:module:id:field(如 user:1001:profile)。used_memory、connected_clients、keyspace_hits/misses、rejected_connections、expired_keys。redis-cli INFO、Prometheus + Grafana、Datadog、RedisInsight。掌握 Node.js + Redis 核心操作與生產級配置,能為高併發系統提供堅實的快取與資料結構基礎設施。