gpt4 book ai didi

node.js - 编写简单的 Node redis 循环(使用 ioredis)的更好方法?

转载 作者:IT王子 更新时间:2023-10-29 05:59:28 24 4
gpt4 key购买 nike

所以,我仍然在很长一段时间内学习其他语言的 JS/Node 方式。

我有一个微型微服务,它从 Redis channel 读取数据,将其临时存储在工作 channel 中,完成工作,删除它,然后继续。如果 channel 中有更多内容,它会立即重新运行。如果没有,它会设置超时并在 1 秒后再次检查。

它工作正常...但超时轮询似乎不是解决此问题的“正确”方法。而且我还没有发现太多关于使用 BRPOPLPUSH 尝试阻止(相对于 RPOPLPUSH)并在 Node 中等待......或其他类似选项的信息。 (发布/订阅在这里不是一个选项......这是唯一的监听器,它可能并不总是在监听。)

这是我正在做的事情的简短要点:

var Redis = require('ioredis');
var redis = new Redis();

var redisLoop = function () {
redis.rpoplpush('channel', 'channel-working').then(function (result) {
if (result) {
processJob(result); //do stuff

//delete the item from the working channel, and check for another item
redis.lrem('channel-working', 1, result).then(function (result) { });
redisLoop();
} else {
//no items, wait 1 second and try again
setTimeout(redisLoop, 1000);
}
});
};

redisLoop();

我觉得我错过了一些非常明显的东西。谢谢!

最佳答案

BRPOPLPUSH 不会在 Node 中阻塞,它会在 client 中阻塞。在这种情况下,我认为这正是您摆脱轮询所需要的。

var Redis = require('ioredis');
var redis = new Redis();

var redisLoop = function () {
redis.brpoplpush('channel', 'channel-working', 0).then(function (result) {
// because we are using BRPOPLPUSH, the client promise will not resolve
// until a 'result' becomes available
processJob(result);

// delete the item from the working channel, and check for another item
redis.lrem('channel-working', 1, result).then(redisLoop);
});
};

redisLoop();

请注意 redis.lrem 是异步的,因此您应该使用 lrem(...).then(redisLoop) 来确保您的下一个 tick 仅在项目已成功从 channel-working 中移除。

关于node.js - 编写简单的 Node redis 循环(使用 ioredis)的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433423/

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