编写简单的 Node redis 循环(使用 ioredis)的更好方法?
Better way to write a simple Node redis loop (using ioredis)?
因此,我仍在学习其他语言的 JS/Node 方法。
我有一个微型微服务,它从 redis 通道读取数据,将其临时存储在工作通道中,完成工作,删除它,然后继续。如果频道中有更多内容,它会立即重新运行。如果没有,它会设置超时并在 1 秒后再次检查。
它工作正常...但超时轮询似乎不是解决此问题的 "correct" 方法。而且我还没有发现太多关于使用 BRPOPLPUSH 尝试阻止(相对于 RPOPLPUSH)并在 Node 中等待......或其他类似选项的信息。 (Pub/Sub 在这里不是一个选项......这是唯一的听众,它可能并不总是在听。)
这是我正在做的事情的简短要点:
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)
来确保您的下一个报价仅在项目从 channel-working
中成功删除后执行。
因此,我仍在学习其他语言的 JS/Node 方法。
我有一个微型微服务,它从 redis 通道读取数据,将其临时存储在工作通道中,完成工作,删除它,然后继续。如果频道中有更多内容,它会立即重新运行。如果没有,它会设置超时并在 1 秒后再次检查。
它工作正常...但超时轮询似乎不是解决此问题的 "correct" 方法。而且我还没有发现太多关于使用 BRPOPLPUSH 尝试阻止(相对于 RPOPLPUSH)并在 Node 中等待......或其他类似选项的信息。 (Pub/Sub 在这里不是一个选项......这是唯一的听众,它可能并不总是在听。)
这是我正在做的事情的简短要点:
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)
来确保您的下一个报价仅在项目从 channel-working
中成功删除后执行。