Redis不会从缓存中检索数据 [英] Redis won't retrieve data from cache

查看:83
本文介绍了Redis不会从缓存中检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循一个教程,我创建了一个cache.js文件,该文件接受猫鼬查询,并通过JSON.stringification将其转换为该查询返回的值的键.目标是将其缓存,然后在mongoose.find()所在的app.js内附加.cache()

I'm following a tutorial and I created a cache.js file that takes the mongoose query and JSON.stringifies it into the key for the values being returned by that query. The goal is to cache that and then append .cache() inside app.js where the mongoose.find() is

当前,如果高速缓存为空,我让它从数据库执行GET,然后将其存储在高速缓存中.我有一个

Currenty if the cache is empty, I have it do a GET from the DB and then store it in the cache. I have a

console.log("CACHE VALUE #2");
console.log(cacheValue1);

确保已存储数据并成功输出数据.这条线有效.但是有了这一行,

that ensures that the data is getting stored and outputs the data successfully. This line works. But with this line,

console.log("CACHE VALUE #1");
console.log(cacheValue);

cacheValue为空.

那是为什么?

它在底部存储值,并且密钥从不更改,因此我不明白为什么它不返回数据而不是null.

It stores at the bottom the value and the key never changes so I don't understand why it won't return the data instead of null.

因此Cache Value #1始终为null,并且Cache Value #2具有正确的数据.

So Cache Value #1 is always null and Cache Value #2 has the correct data.

控制台输出:

GRABBING FROM DB
CLIENT CONNECTION STATUS: true
Setting CACHE to True
ABOUT TO RUN A QUERY
{"$and":[{"auctionType":{"$eq":"publicAuction"}},{"auctionEndDateTime":{"$gte":1582903244869}},{"blacklistGroup":{"$ne":"5e52cca7180a7605ac94648f"}},{"startTime":{"$lte":1582903244869}}],"collection":"listings"}
CACHE VALUE #1
null
CACHE VALUE #2
(THIS IS WHERE ALL MY DATA SHOWS UP)

const mongoose = require('mongoose');
const redis = require('redis');
const util = require('util');
var env = require("dotenv").config({ path: './.env' });

const client = redis.createClient(6380, process.env.REDISCACHEHOSTNAME + '.redis.cache.windows.net', {
  auth_pass: process.env.REDISCACHEKEY,
  tls: { servername: process.env.REDISCACHEHOSTNAME + '.redis.cache.windows.net' }
});


client.get = util.promisify(client.get);


const exec = mongoose.Query.prototype.exec;

mongoose.Query.prototype.cache = function () {
  this.useCache = true;
  console.log("Setting CACHE to True")
  return this;
}

mongoose.Query
  .prototype.exec = async function () {
    if (!this.useCache) {
      console.log("GRABBING FROM DB")
      console.log("CLIENT CONNECTION STATUS: " + client.connected);

      return exec.apply(this, arguments);
    }

    console.log("ABOUT TO RUN A QUERY")
    const key = JSON.stringify(Object.assign({}, this.getQuery(), {
      collection: this.mongooseCollection.name
    }));


    //See if we have a value for 'key' in redis
    console.log(key);
    const cacheValue = await client.get(key);
    console.log("CACHE VALUE #1");
    console.log(cacheValue);
    //If we do, return that
    if (cacheValue) {
      console.log("cacheValue IS TRUE");
      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);

    let redisData = JSON.stringify(result);
    //stores the mongoose query result in redis



    await client.set(key, JSON.stringify(redisData)), function (err) {
      console.error(err);

    }
    const cacheValue1 = await client.get(key);
    console.log("CACHE VALUE #2");
    console.log(cacheValue1);




    return result;
  }


推荐答案

基于您链接的 pastebin ,您的查询使用作为其值.这意味着每次运行查询时,时间戳记的值都不同.

Based on the pastebin you linked, your queries are using Date.now() for their values. This means that each time a query is run, you have different values for the timestamp.

因为您的键是实际的查询,并且查询具有基于Date.now()的动态值,所以您的键永远不会相同,这就是为什么您以后无法在缓存中找到它们的原因,每个查询都会生成一个唯一键,因为Date.now()的动态值.

Because your keys are the actual query, and the query has dynamic values based on Date.now(), your keys will never be the same, which is why you can't find them in the cache later, each query is generating a unique key because of the dynamic values of Date.now().

这篇关于Redis不会从缓存中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆