学习

使用 Redis Hashes 管理领域对象

Simon Prickett
作者
Simon Prickett, Redis 首席开发者倡导者

在本模块中,您将了解我们如何使用 Redis Hashes 对应用程序中的用户和位置数据进行建模。

编码练习#

在您的第一个编码练习中,您将添加一个新的路由,该路由接受用户 ID 并返回其全名。

使用您的 IDE 打开您克隆 GitHub 仓库的node-js-crash-course文件夹。打开文件src/routes/user_routes.js并找到路由/user/:userId/fullname,它看起来像这样

// EXERCISE: Get user's full name.
router.get(
  '/user/:userId/fullname',
  [param('userId').isInt({ min: 1 }), apiErrorReporter],
  async (req, res) => {
    const { userId } = req.params;
    /* eslint-disable no-unused-vars */
    const userKey = redis.getKeyName('users', userId);
    /* eslint-enable */

    // TODO: Get the firstName and lastName fields from the
    // user hash whose key is in userKey.
    // HINT: Check out the HMGET command...
    // https://redis.ac.cn/commands/hmget
    const [firstName, lastName] = ['TODO', 'TODO'];

    res.status(200).json({ fullName: `${firstName} ${lastName}` });
  },
);

在本练习中,您将修改代码,通过从 Redis 检索请求用户的 firstName 和 lastName 字段来返回用户的全名。

首先,确保您的服务器仍在运行,如果没有,请使用以下命令启动它:

$ npm run dev

接下来,浏览至http://localhost:8081/api/user/5/fullname

您应该看到

{
  "fullName": "TODO TODO"
}

请查看Redis HMGET 命令文档,该命令从 Redis Hash 中检索多个命名字段。您需要添加代码来调用 Redis 客户端的hmget函数,然后将返回的值放入firstNamelastName变量中。您应该能够通过一次调用hmget来检索这两个值。有关如何调用 Redis 命令的指导,请查看调用HGETALL命令的/user/:userId路由的代码。

每次保存更改时,nodemon 都会自动为您重启服务器。

准备好测试您的解决方案时,浏览至http://localhost:8081/api/user/5/fullname,您应该看到

{
  "fullName": "Alejandro Reyes"
}

如果您需要我们团队的帮助,请加入我们的 Discord

外部资源#

在此视频中,Justin 解释了什么是 Redis Hashes,并展示了常用的 Redis Hash 命令如何工作