Redis®*: 使用Node.js的Redis代码示例
本文档属于实时排名用户指南的一部分。您可以在此处查看完整指南:学习如何使用Redis实时为200万用户按分数排名。
👋 欢迎来到 Stackhero 文档!
Stackhero 提供现成的 Redis 云 解决方案,具有众多优势,包括:
- 包含
Redis Commander网页界面。- 无限消息大小和传输。
- 只需点击即可轻松更新。
- 由专用私有 VM提供的最佳性能和强大安全性。
节省时间,简化生活:只需 5 分钟即可试用 Stackhero 的 Redis 云托管 解决方案!
在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();
})();
这个简单而强大的代码片段非常适合管理实时排名数据。