Redis®*: 使用 Node.js 的 Redis 代碼示例

此文件屬於即時排名用戶指南的一部分。請在此處查看完整指南:學習如何使用 Redis 即時為 200 萬用戶按分數排名

👋 歡迎來到 Stackhero 文件!

Stackhero 提供一個即用型的 Redis cloud 解決方案,帶來多項好處,包括:

  • 包含 Redis Commander 網頁介面
  • 無限制的訊息大小和傳輸。
  • 只需一鍵即可輕鬆進行 更新
  • 專用私有 VM 提供的最佳 效能 和強大 安全性

節省時間簡化生活:只需 5 分鐘 即可嘗試 Stackhero 的 Redis cloud hosting 解決方案!

在 Redis Commander 中驗證概念後,是時候將 Redis 集成到實際代碼中了。我們的客戶使用 Node.js,以下是使用 ioredis 作為客戶端的示例:

const Redis = require('ioredis');

(async () => {
  // 設置 Redis 憑證
  // 如果您使用 Stackhero,您可以在 Stackhero 儀表板上找到這些
  const redis = new Redis({
    host: '<redisServerHost>',
    password: '<redisServerPassword>',
    port: <PORT_TLS>, // <PORT_CLEAR> 用於非加密連接,<PORT_TLS> 用於 TLS。應使用 TLS。
    tls: {}, // 提供一個空對象以啟用 TLS
    lazyConnect: true
  });

  // 連接到 Redis
  await redis.connect();

  // 添加用戶
  await redis.zadd('usersScores', 11, 'userId1');
  await redis.zadd('usersScores', 54, 'userId2');
  await redis.zadd('usersScores', 24, 'userId3');

  // 檢索 userId1 的分數
  const score = await redis.zscore('usersScores', 'userId1');
  console.log('userId1 有 ' + score + ' 分');

  // 檢索 userId1 的排名位置
  const rankPosition = await redis.zrevrank('usersScores', 'userId1');
  console.log('userId1 排名在位置 ' + rankPosition);

  // 從 Redis 斷開連接
  await redis.disconnect();
})();

這個簡單但強大的代碼片段非常適合管理即時排名數據。