我試圖創建工人,它工作正常。它有四個內核,多次嘗試時,它只顯示來自一名工作人員的消息。節點js集羣 - 它是如何工作的
var app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
if (cluster.isMaster) {
var cpuCount = os.cpus().length ;
console.log("No. of cpus:", cpuCount);
for(var i = 0; i < cpuCount; i++) cluster.fork();
cluster.on('listening', function(worker, address) {
console.log('woker id:' + worker.id +' is now listening on port:' + address.port);
});
} else {
console.log("i'm a worker.. ... lets proceed");
var server = app.listen(8082, function(req, res) {
var host = server.address().address;
var port = server.address().port;
request(i18n.__('url.config'), function(error, response, body){
if (!error && response.statusCode == 200) {
} else {
console.log("Config error",error);
}
});
}); // child process
}// else
//Listen for dying workers
cluster.on('exit', function (worker) {
// Bring that ... ..er back
console.log('Worker %d died :', worker.id);
cluster.fork();
});
cluster.on('online', function (worker) {
// worker is alive
console.log('Worker %d is alive :', worker.id);
});
app.get('/hey', function(req, res){
console.log('Worker %d running!', cluster.worker.id);
res.send('Hello World from worker ' + cluster.worker.id);
});
後來我修改了代碼來實例化並在worker(else循環)中創建表達對象的創建。輸出是一樣的。
if (cluster.isMaster) {
var cpuCount = os.cpus().length ;
console.log("No. of cpus:", cpuCount);
for(var i = 0; i < cpuCount; i++) cluster.fork();
cluster.on('listening', function(worker, address) {
console.log('woker id:' + worker.id +' is now listening on port:' + address.port);
});
} else {
var app = express();
console.log("i'm a worker.. ... lets proceed");
var server = app.listen(8082, function(req, res) {
var host = server.address().address;
var port = server.address().port;
request(i18n.__('url.config'), function(error, response, body){
if (!error && response.statusCode == 200) {
} else {
console.log("Config error",error);
}
});
app.get('/hey', function(req, res){
console.log('Worker %d running!', cluster.worker.id);
res.send('Hello World from worker ' + cluster.worker.id);
});
}); // child process
}// else
節點--debug server.js
調試端口監聽5858
CPU的數目:4
調試器監聽端口5859
調試器聽在港口5860
調試器偵聽端口5861
調試端口監聽5862
我是一個工人......讓繼續
woker ID:1現在偵聽端口:8082
我是一個工人......讓繼續
我是一個工人......讓繼續
我是一個工人......讓繼續
woker ID:4現在監聽端口:8082
woker ID:3現在監聽端口:8082
woker ID:2現在監聽端口:8082
工2跑步!
工人2正在運行!
工人2正在運行!
工人2正在運行!
哪種工作者創作方式正確?自從它在港口收聽以來,在全球範圍內創建表達對象會造成任何問題?
感謝,對xplanation和紐帶。 – Martin