在 scripts/ 目录中,有一个名为 loadRedis.js 的文件。其内容如下:
const redis = require('redis')
const fs = require('fs');
const path = require('path');
const raw = fs.readFileSync(path.resolve( __dirname, 'games.json'));
const games = JSON.parse(raw)
const client = redis.createClient({
url: `redis://${process.env.REDIS_ENDPOINT}`
})
client.on('error', function(err) {
console.log('Received Redis error:', err)
})
games.forEach((game) => {
const gametime = new Date(game.gamedate)
const key = `${game.username}|${game.gamedate}|${game.level}`
client.multi()
.zadd('Overall Leaderboard', game.score, key)
.zadd(`Monthly Leaderboard|${gametime.getUTCMonth()}-${gametime.getUTCFullYear()}`, game.score, key)
.zadd(`Daily Leaderboard|${gametime.getUTCDay()}-${gametime.getUTCMonth()}-${gametime.getUTCFullYear()}`, game.score, key)
.exec((err) => {
if (err) {
console.log('Error: ', err);
}
})
})
console.log('Loaded data!')
client.quit()
如同 pingRedis.js 脚本一样,您正在创建 Redis 客户端。然后,将所有游戏数据读取到内存。对于每个游戏元素,您都需将其写入 Redis 三次:一次写入总排行榜、一次写入每周排行榜、一次写入每日排行榜。每次写入操作都在 Redis 中使用 ZADD 命令,将元素添加到有序集合中。
请注意整体有序集合键名以及有序集合中元素名的结构。
对于有序集合键名,总排行榜就是 Overall Leaderboard。对于每月和每日排行榜,则会包含日期信息。因此,2019 年 11 月的每月排行榜键名是 Monthly Leaderboard|11-2019,2019 年 11 月 8 日的每日排行榜键名是 Daily Leaderboard|8-10-2019。这种命名 scheme 让您能够在读取时时发现合适的排行榜键。
现在,查看元素插入到表中时的键名。它由用户名、时间戳和关卡组成。将所有这些信息编码到键名中,这样,应用程序在获取总体高分时会显示有关高分的其他相关信息。
使用以下命令执行 loadRedis.js 脚本: