我对Redis和Node.JS并不陌生,我一直试图将这两者结合起来。然而,我有一点困惑,我可以使用一个又一个的功能。
随着数据库大小的增长,以下代码似乎同步运行:
client.dbsize(function(err, numKeys) {
console.log("DB Size before hashes added" + numKeys);
return numKeys;
});
for (var i = 0; i < 100; i++) {
client.hmset(i, "username", "username", "answer", "answer");
client.zadd('answer', i, i);
};
client.dbsize(function(err, numKeys) {
console.log("DB Size after hashes added" + numKeys);
return numKeys;
});但是,当我尝试查询排序集‘答案’以返回数组时,这个数组'reply‘在回调'zrevrangebyscore’之外的其他redis函数中是不可用的。
client.zrevrangebyscore('answer', 100, 0, function(err, reply) {
console.log (reply);
return reply;
});例如,在reply1上调用的后续“hgetall”函数返回未定义的函数。我是应该以异步的方式使用所有Redis函数(包括hmset和dbsize)、回调/client.Multiple等,还是在同步使用的情况下有效地完成一些工作?所有的帮助都很感激。
发布于 2015-10-18 23:29:01
红色是单线程的。,所以在Redis上的命令是,总是按顺序执行。看起来您可能正在为Redis使用异步客户端,这就是混乱的根源所在。因为您无法保证网络延迟,所以如果您使用的是异步Redis客户端,那么稍后的调用可能会在较早的调用之前击中Redis服务器,并导致所遇到的问题。对于为什么Redis的异步客户端存在于这里中,有一个非常好的解释。
尽管如此,在您的情况下,重要的一点是,如果您希望保证您的命令同步运行,那么您有几个选项:
发布于 2015-10-17 12:44:11
当涉及到同步和异步代码时,您似乎很困惑。我建议你尽可能多地阅读,直到它“点击”。我将举一个例子,说明出了什么问题,以及为什么:
//we're going to fake the redis dbSize function
var dbSize = function(callback){
//always finishes asynchronously
console.log("dbsize called");
setTimeout(callback, 1000);
};
//here we get to your code
dbSize(function(){
console.log("First callback");
});
console.log("synchronous redis method calls");
//here come the synchronous redis methods, that finish synchronously
dbSize(function(){
console.log("Second callback");
});现在,如果您使用运行以下代码,它会将以下内容输出到控制台:
"dbsize called"
"synchronous redis method calls"
"dbsize called"
"First callback"
"Second callback"如您所见,在异步方法完成之前,同步方法将被调用。所以,要做到的就是确保之后调用同步方法,这将在第一个回调中进行,也就是说,您必须将这些东西链接在一起。现在这很混乱,因为它会让你回到地狱:
dbSize(function(){
console.log("First callback");
console.log("synchronous redis method calls");
//here come the synchronous redis methods, that finish synchronously
dbSize(function(){
console.log("Second callback");
});
})因此,为了避免这种情况,最好使用类似于异步库的
async.series([
function(next){
dbSize(next);
},
function(next){
console.log("synchronous redis method calls");
//here come the synchronous redis methods, that finish synchronously
next();
},
function(next){
dbSize(next);
},
], function(){
console.log('All done!');
})这将产生以下结果:
"dbsize called"
"synchronous redis method calls"
"dbsize called"
"All done!"https://stackoverflow.com/questions/33186461
复制相似问题