Redis 是 Node.js 應用最常見的搭配夥伴之一,無論是當快取、Session 儲存還是簡單的任務佇列都很順手。本文示範如何用 node_redis 完成基本的寫入、讀取、設定過期時間與查詢剩餘存活時間。
開始之前,請先確認 Redis 伺服器、Node.js 以及 Node 的 Redis 擴充 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
快取情境下,過期時間往往比值本身更重要。下面用一個定時器反覆讀取,觀察值在 3 秒後消失:
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); // 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
提醒一句:這裡的定時器純粹是為了展示 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);
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
把 set 與 expire 分開呼叫有個實務上的小陷阱:若兩者之間程序崩潰,就會留下永不過期的 key。此時可以改用 setex(或 SET 搭配 EX 選項)一次完成寫值與設定 TTL,語意更安全。