DIV CSS 佈局教程網

在 Node.js 中讀寫 Redis:從基本操作到 TTL 應用
編輯:JavaScript綜合知識     

Redis 是記憶體型的高速資料庫,常用於快取、計數器、Session 存放與簡易佇列。本文示範如何從 Node.js 透過 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

所有指令都是非同步的,結果一律透過回呼函式取得——這是 Redis 用戶端與 MySQL 這類同步風格函式庫最大的不同。

用 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);        // 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

要留意這裡的計時器純粹是為了讓你能肉眼觀察 TTL 的行為,實際專案中請勿用這種方式輪詢。

用 TTL 查詢剩餘存活秒數

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 可以直接帶過期時間。Redis 2.6.12 之後 SET key value EX 3 一行就能完成,不必再拆成兩次往返,也避免了「set 成功但 expire 失敗」的窗口。

TTL 回傳 -1 與 -2 是有意義的。-1 表示 key 存在但沒有設定過期時間,-2 表示 key 不存在。判斷時別只當成一般數字。

連線錯誤一定要處理。Redis 掛掉或網路中斷時,若沒有 error 監聽,Node 行程可能直接結束。正式環境建議加上重連機制與 unref() 的考量。

Redis 的單執行緒模型決定了它的效能特性。阻塞型指令(KEYS、大範圍 SMEMBERS)會卡住整個服務,請改用 SCAN 系列做迭代。另外,新版用戶端(node-redis v4 以上)已改為 Promise 介面,await client.get(key) 比层层回呼好讀得多,新專案建議直接採用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved