我已经使用 node_redis
设置了一个应用程序,我正在尝试让简单的 get/set 工作。
似乎我可以插入到缓存中,但我希望能够检查 key 是否存在。
在 C# 中,我会做类似这样的事情:if(Cache["mykey"] == null)
。
如何进行支票?我应该用 if(!client.get[cacheKey]) {
替换什么?
我的代码:
app.get('/users',function(req,res) {
var cacheKey = 'userKey';
if(!client.get[cacheKey]) {
mongoose.model('users').find(function(err,users) {
console.log('Setting cache: ' + cacheKey);
client.set(cacheKey,users,redis.print);
res.send(users);
});
} else {
console.log('Getting from cache: ' + cacheKey);
return client.get[cacheKey];
}
});
最佳答案
这里要注意的最重要的一点是,redis 客户端和 node 中的大多数其他东西一样,不是同步的。
您访问 client.get
的方式暗示它是 Javascript 中的一个数组。它实际上是一个函数,如 mongoose.find
,期望回调作为最后一个参数。在这种情况下,您只需先传递 cacheKey
。您的 if
子句在回调中。
client.get(cacheKey, function(err, data) {
// data is null if the key doesn't exist
if(err || data === null) {
mongoose.model('users').find(function(err,users) {
console.log('Setting cache: ' + cacheKey);
client.set(cacheKey,users,redis.print);
res.send(users);
});
} else {
return data;
}
});
如果您的 if 语句后面有任何代码,就好像它是同步的一样,它很可能也应该放在回调函数中。
关于node.js - 使用 node_redis 在 node.js 应用程序中使用 redis 检查缓存键是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24861451/