Redis 作為高效能的記憶體資料結構存儲,廣泛應用於快取、Session 管理、即時排行榜等場景。本文將帶領你在 Node.js 環境中,從零開始建立 Redis 連線,掌握基本的鍵值操作,並深入探討鍵過期策略與 TTL(存活時間)監控技巧。
開始前,請確保已安裝以下組件:
npm install redis(本文基於 redis v3.x 版本示範)創建 app.js,編寫基礎連線邏輯:
const redis = require('redis');
const client = redis.createClient(); // 預設連線 localhost:6379
client.on('error', (err) => console.error('Redis 連線錯誤:', err));
client.on('connect', () => {
console.log('Redis 連線成功');
runSample();
});
function runSample() {
// 設定鍵值
client.set('string key', 'Hello World', (err, reply) => {
console.log('SET 回應:', reply); // 輸出 OK
});
// 讀取鍵值
client.get('string key', (err, reply) => {
console.log('GET 回應:', reply); // 輸出 Hello World
});
}
執行 node app.js,終端機將顯示:
Redis 連線成功
SET 回應: OK
GET 回應: Hello World
透過 EXPIRE 指令讓鍵在指定秒數後自動刪除:
function runSampleWithExpire() {
client.set('string key', 'Hello World', redis.print);
client.expire('string key', 3); // 3 秒後過期
// 示範用:每秒輪詢鍵狀態
const timer = setInterval(() => {
client.get('string key', (err, reply) => {
if (reply) {
console.log('存活中:', reply);
} else {
clearInterval(timer);
console.log('鍵已過期');
client.quit();
}
});
}, 1000);
}
輸出範例:
Reply: OK
存活中: Hello World
存活中: Hello World
存活中: Hello World
鍵已過期
結合 TTL 指令,可精確掌握鍵剩餘壽命:
function runSampleWithTTL() {
client.set('string key', 'Hello World', redis.print);
client.expire('string key', 3);
const timer = setInterval(() => {
client.get('string key', (err, reply) => {
if (reply) {
console.log('存活中:', reply);
client.ttl('string key', (err, ttl) => {
console.log('剩餘 TTL:', ttl);
});
} else {
clearInterval(timer);
console.log('鍵已過期');
client.quit();
}
});
}, 1000);
}
輸出將顯示 TTL 從 2 遞減至 0:
Reply: OK
存活中: Hello World
剩餘 TTL: 2
存活中: Hello World
剩餘 TTL: 1
存活中: Hello World
剩餘 TTL: 0
鍵已過期
setInterval 輪詢:示範代碼中的定時器僅為教學用途。實際專案建議使用 Redis Keyspace Notifications 或獨立排程服務處理過期邏輯。redis.createClient() 選項配置連線池,或改用 ioredis 等支援集群的客戶端。error 事件,並實作重連機制(retry_strategy)。本文示範了 Node.js 串接 Redis 的核心流程:建立連線、基本 CRUD、過期時間設定與 TTL 監控。掌握這些基礎後,你可以進一步探索 Redis 的資料結構(Hash、List、Set、Sorted Set)、發布/訂閱、Lua 腳本等進階功能,構建高效能的後端服務。