Redis 是 Node.js 應用最常搭配的資料結構儲存之一,無論當快取、Session 儲存還是簡易佇列都很合適。本文從最基礎的連線與讀寫開始,再談談如何設定 key 的過期時間。
開始之前,請先確認 Redis 伺服器已啟動,Node.js 已安裝,並且透過 npm 裝好 node_redis 這個用戶端套件。
新增一個 app.js:
var redis = require("redis"),
client = redis.createClient();
client.on("error", function (err) {
console.log("Error " + err);
});
client.on("connect", runSample);
function runSample() {
// 寫入
client.set("string key", "Hello World", function (err, reply) {
console.log(reply.toString());
});
// 讀取
client.get("string key", function (err, reply) {
console.log(reply.toString());
});
}
連線建立後觸發 runSample,先寫入再讀出,輸出結果是:
OK
Hello World
所有指令都是非同步的,回呼函式的第二個參數才是回應內容。這是使用 node_redis 時必須先建立的習慣。
快取情境下,「什麼時候自動失效」往往比「怎麼存」更重要。Redis 的 expire 指令以秒為單位設定存活時間:
var redis = require('redis'),
client = redis.createClient();
client.on('error', function (err) {
console.log('Error ' + err);
});
client.on('connect', runSample);
function runSample() {
client.set('string key', 'Hello World', redis.print);
// 3 秒後過期
client.expire('string key', 3);
// 以下定時器僅為展示 TTL 效果,實際專案請謹慎使用
var myTimer = setInterval(function () {
client.get('string key', function (err, reply) {
if (reply) {
console.log('I live: ' + reply.toString());
} else {
clearInterval(myTimer);
console.log('I expired');
client.quit();
}
});
}, 1000);
}
輸出會像這樣,值在第三秒後消失:
Reply: OK
I live: Hello World
I live: Hello World
I live: Hello World
I expired
這裡的 setInterval 只是為了讓你能在終端看到變化過程。Node 的行程是單執行緒的,長期跑著的定時器會實際佔用資源,正式環境請改用 Redis 自身的通知機制或箭頭式的 TTL 監聽方案。
想知道還剩多久,用 ttl 指令。它回傳剩餘秒數;若 key 沒有設定過期時間則回傳 -1,key 已不存在則回傳 -2:
var redis = require('redis'),
client = redis.createClient();
client.on('error', function (err) {
console.log('Error ' + err);
});
client.on('connect', runSample);
function runSample() {
client.set('string key', 'Hello World', redis.print);
client.expire('string key', 3);
var myTimer = setInterval(function () {
client.get('string key', function (err, reply) {
if (reply) {
console.log('I live: ' + reply.toString());
client.ttl('string key', writeTTL);
} else {
clearInterval(myTimer);
console.log('I expired');
client.quit();
}
});
}, 1000);
}
function writeTTL(err, data) {
console.log('I live for this long yet: ' + data);
}
執行結果:
Reply: OK
I live: Hello World
I live for this long yet: 2
I live: Hello World
I live for this long yet: 1
I live: Hello World
I live for this long yet: 0
I expired
倒數的過程一目了然。
Redis 的 key 有兩種常見寫法可以簡化流程:setex 一次完成寫入加重設時限,set 搭配 EX 選項也是;比起分兩次呼叫 set 與 expire,這兩者能避免「設定了值卻還沒設過期就當機」的縫隙。另外,正式環境記得為 error 事件掛上處理器並加入重連機制,預設的離線行為在長時間連線下容易讓人誤判。