2015-09-05 65 views
2

我使用Redis的客户端的node.js的Node.js /让Redis的异步调用

var db = require("redis"); 
    var dbclient = db.createClient(); 

我加载DB在接下来的方式:

dbclient.zrange("cache", -1000000000000000, +1000000000000000, function(err, replies){ 
       logger.info("Go to cache"); 
       for (var i=0; i < replies.length; i++){ 
        (function(i){ 
        // Do some commands with the result 
        })(i) 
       } 
    }) 

我注意到,在我的应用程序启动,需要30秒。用于执行数据库查询。此时,没有其他来自Express模块的请求被提供。

我该如何解决这个问题?为什么不是异步?

+1

API。但'循环' - 没有。 –

+0

什么是_“用结果做一些命令”_?什么是'answers.length'? – robertklep

回答

3

如果你担心的正常运行时间,那么你应该使用ZSCAN

使用COUNT选项来获得在每次调用更多的数据,但要记住:

虽然SCAN不提供有关数量的保证在每次迭代返回的元素,就可以使用COUNT选项

,并在每个结果使用setImmediate功能伊特经验调整扫描的行为转入下一个SCAN。

var cursor = '0'; 

function doscan(){ 
    dbclient.zscan("cache", cursor, "COUNT", "100", function(err, replies){ 
       logger.info("Go to cache"); 

       // Update the cursor position for the next scan 
       cursor = res[0]; 

       if (cursor === '0') { 
        return console.log('Iteration complete'); 
       } else { 
        for (var i=0; i < replies.length; i++){ 
         (function(i){ 
         // Do some commands with the result 
         })(i) 
        } 
        setImmediate(function() { doscan() }); 
       } 
    }) 
} 
1

正如stdob所说,您的代码中唯一不是异步的部分是for循环部分。就个人而言,我会创建一个child process并运行数据库查询以及您决定对输出执行的任何操作。如果这不适用于您的应用程序,那么您可能需要延迟启动程序30秒或以不同方式处理缓存。