使用Node.js群集支持,我希望主进程生成添加到Redis队列的数据项。然后,我想运行多个读取Redis队列的工作进程。当然,只有一个工作进程应该使用从队列中检索的数据项。
为了让我开始,您能否建议在哪里查看Node包支持或原始Redis命令来实现此目的?让我强调消费者是Node.js集群环境中的独立进程,我们可以调整竞争从单个Redis队列读取的工作进程数,以调整整体系统性能。
答案 0 :(得分:6)
看起来kue正是我们所需要的。
在Node.js集群环境中通过Redis进行最少的测试程序排队任务:
// cluster-queue.js
var kue = require('kue');
var cluster = require('cluster');
var numWorkers = process.argv[2];
var numParallel = process.argv[3];
var jobDelay = process.argv[4];
var numJobs = process.argv[5];
if (process.argv.length !== 6) {
console.log('Usage: node cluster-work-queue <numWorkers> <numParallel> <jobDelay> <numJobs>');
process.exit(1);
}
var jobs = kue.createQueue();
var jobType = 'someTask';
if (cluster.isMaster) {
for (var i = 0; i < numWorkers; i++) {
cluster.fork();
}
for (var j = 0; j < numJobs; j++) {
(function(count) {
var data = { count: count };
jobs.create(jobType, data).save(function(err) {
if (err) {
console.log('jobs.create', err);
} else {
console.log('master', 'jobs.create', count);
}
});
})(j);
}
} else {
jobs.process(jobType, numParallel, function(job, done){
console.log('worker', cluster.worker.id, 'jobs.process', job.data);
setTimeout(function() { done(); }, jobDelay);
});
}
示例运行(注意调整工作人员计数的命令行选项等):
[jfathman@cloud node]$ node cluster-queue.js 2 1 20 10
master jobs.create 0
master jobs.create 1
master jobs.create 2
master jobs.create 3
master jobs.create 4
master jobs.create 5
master jobs.create 6
master jobs.create 7
master jobs.create 8
master jobs.create 9
worker 1 jobs.process { count: 0 }
worker 2 jobs.process { count: 1 }
worker 1 jobs.process { count: 2 }
worker 2 jobs.process { count: 3 }
worker 1 jobs.process { count: 4 }
worker 2 jobs.process { count: 5 }
worker 1 jobs.process { count: 6 }
worker 2 jobs.process { count: 7 }
worker 1 jobs.process { count: 8 }
worker 2 jobs.process { count: 9 }
^C