[英]how to redis cache set and get properly used in nodejs?
我使用mongodb嘗試了node.js crud操作,並且還存儲在redis緩存中。 我第一次嘗試運行get方法從db獲取數據,第二次運行get方法。 它從緩存中獲取數據,但我試圖刪除表中的數據,另一次運行get方法,它沒有顯示數據。它顯示空數據。 但是數據存儲在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.py
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
仍未定義。
解決這個問題的最簡單方法是使用回調調用Get_Value
,以便在redis 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 )
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.