萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js 整合 Redis 完整入門指南:從連線到進階過期控制

前言

Redis 作為高效能的記憶體資料結構存儲,廣泛應用於快取、Session 管理、即時排行榜等場景。本文將帶領你在 Node.js 環境中,從零開始建立 Redis 連線,掌握基本的鍵值操作,並深入探討鍵過期策略與 TTL(存活時間)監控技巧。

環境準備

開始前,請確保已安裝以下組件:

  • Redis 伺服器(本地或遠端)
  • Node.js(建議 v14+)
  • Node.js Redis 客戶端套件:npm install redis(本文基於 redis v3.x 版本示範)

建立第一個 Redis 連線

創建 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

實作鍵過期與 TTL 監控

使用 EXPIRE 設定存活時間

透過 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 剩餘秒數

結合 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 腳本等進階功能,構建高效能的後端服務。

copyright © 萬盛學電腦網 all rights reserved