首页 > 解决方案 > 如何将整个数据对象存储在 Redis 中(不仅仅是未水合的数据)?

问题描述

我正在尝试在我的 Redis 存储中设置整个用户对象。USer 有他们喜欢的名称和音乐数组之类的东西。

当我使用 HSET 在 redis 中设置密钥时。我注意到它不是数据集的几个部分。基本没水分。

我也试过HMSET。

这是我在做什么的代码片段:

mongoose.Query.prototype.exec = async function() {
  if (!this.useCache) {
    return exec.apply(this, arguments);
  }

  const key = JSON.stringify(
    Object.assign({}, this.getQuery(), {
      collection: this.mongooseCollection.name
    })
  );
  //See if we have a value for 'key' in redis
  const cacheValue = await client.hget(this.hashKey, key);

  //If we do, return that
  if (cacheValue) {
    //console.log("From cache");
    const doc = JSON.parse(cacheValue);

    return Array.isArray(doc)
      ? doc.map(d => new this.model(d))
      : new this.model(doc);
  }

  //Otherwise, issue the query and store the result in redis
  const result = await exec.apply(this, arguments);

  client.hset(this.hashKey, key, JSON.stringify(result));

  if (this.mongooseCollection.name !== "systems") {
    client.expire(this.hashKey, 1800); // 30 minutes cache
  }

  //console.log("Saved hashkey to cache");

  return result;
};```

I would like to get the entire object back.

标签: node.jsredisnode-redis

解决方案


推荐阅读