我尝试使用mongodb节点js crud操作并存储在redis缓存中。第一次我尝试运行get方法从db获取数据,第二次运行get方法从缓存获取数据。但我试图删除表中的数据和另一个运行get方法的时间它没有显示data.its显示空数据。但是数据存储在redis缓存中如何解决这个问题
cache.js
// var asyncRedis = require("async-redis")
// var myCache = asyncRedis.createClient()
var redis = require('redis');
const client = redis.createClient()
client.on('connect', function () {
console.log('Redis client connected');
});
client.on('error', function (err) {
console.log('Something went wrong ' + err);
});
var value;
var todayEnd = new Date().setHours(23, 59, 59, 999);
function Get_Value()
{
client.get('products', function(err,results) {
value = JSON.parse(results);
})
return value
}
function Set_Value(products)
{
client.set('products', JSON.stringify(products))
client.expireat('products', parseInt(todayEnd/1000));
}
exports.get_value = Get_Value;
exports.set_value = Set_Value;
routes.朋友
data = cache.get_value()
console.log(data)
if (data) {
console.log("GET")
res.send(data)
}
else {
console.log("SET")
const r = await db.collection('Ecommerce').find().toArray();
res.send(r)
data = cache.set_value(r)
}
当天,
你的Get_Value
对我来说有点奇怪。 Redis get将以异步方式执行。因此,当您将return value
语句放在回调之外时,它将立即返回,value
仍未定义。
解决这个问题的最简单方法是在redis Get_Value
返回时调用带有回调的GET
。
function Get_Value(callback) {
client.get('products', function(err,results) {
let value = JSON.parse(results);
>> callback(value);
});
}
你可以这样使用它:
Get_Value(function(value) {
console.log("products: " + value);
}
另一种选择是使用Node Redis的Promise API(参见文档:https://github.com/NodeRedis/node_redis)
这有帮助吗?