gpt4 book ai didi

Node.js/使redis调用异步

转载 作者:IT王子 更新时间:2023-10-29 06:03:35 27 4
gpt4 key购买 nike

我在node.js中使用redis客户端

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

我用下一种方式加载数据库:

 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 模块没有提供其他请求。

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

最佳答案

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

使用 COUNT 选项可以在每次通话中获取更多数据,但请记住:

While SCAN does not provide guarantees about the number of elements returned at every iteration, it is possible to empirically adjust the behavior of SCAN using the COUNT option

并且在每个结果中使用 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() });
}
})
}

关于Node.js/使redis调用异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32411609/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com