我有一个基于 SailsJs ( http://sailsjs.org/ ) 的应用程序,它必须处理一些 CPU 密集型任务。简而言之,我想使用cluster
(https://nodejs.org/api/cluster.html)模块将这些任务的处理委托给工作进程,这样 Sails 应用程序的主事件循环就不会被阻塞(并且所以可以正常响应请求)。
创建工作人员时,我收到一个EADDRINUSE
错误,因为 Sails 试图再次运行并绑定到同一个端口。
示例代码:
// SomeSailsService.js
var cluster = require('cluster');
var Queue = require('bull');
var myQueue = Queue('myQueue', 'connection stuff', 'etc');
var numWorkers = 2;
var i;
if (cluster.isMaster) {
// Spawn some workers
for (i = 0; i < numWorkers; i++) {
cluster.fork();
}
} else {
// This is a worker, so bind to new job event
myQueue.process(function processJob(job, done) {
// CPU intensive shenanigans
});
}
module.exports = {
addToQueue: function(foo) {
myQueue.add({foo: foo});
}
};
运行上述程序时,Sails 应用程序启动,然后在启动两个工作人员时尝试再启动应用程序两次。这会导致以下两个错误:
events.js:72
throw er; // Unhandled 'error' event
^
Error: bind EADDRINUSE
at errnoException (net.js:904:11)
at net.js:1084:30
at Object.1:1 (cluster.js:594:5)
at handleResponse (cluster.js:171:41)
at respond (cluster.js:192:5)
at handleMessage (cluster.js:202:5)
at process.emit (events.js:117:20)
at handleMessage (child_process.js:322:10)
at child_process.js:396:7
at process.handleConversion.net.Native.got (child_process.js:91:7)
at process.<anonymous> (child_process.js:395:13)
at process.emit (events.js:117:20)
at handleMessage (child_process.js:322:10)
at Pipe.channel.onread (child_process.js:347:11)
有没有解决的办法?或者解决这个问题的另一种方法?