Modulo di elaborazione del cluster Node.js
Esempio
Esegui il codice tre volte, la prima volta come master, poi come worker:
var cluster = require('cluster');
if (cluster.isWorker) {
console.log('I am a worker');
} else {
console.log('I am a
master');
cluster.fork();
cluster.fork();
}
Definizione e utilizzo
Il modulo cluster fornisce un modo per creare processi figlio che vengono eseguiti contemporaneamente e condividono la stessa porta del server.
Node.js esegue la programmazione a thread singolo, che è molto efficiente in termini di memoria, ma per sfruttare i sistemi multi-core dei computer, il modulo Cluster consente di creare facilmente processi figlio che ciascuno esegue sul proprio thread singolo, per gestire il carico.
Sintassi
La sintassi per includere il modulo cluster nell'applicazione:
var cluster = require('cluster');
Proprietà e metodi del cluster
Method | Description |
---|---|
disconnect() | Disconnects all workers |
exitedAfterDisconnect | Returns true if a worker was exited after disconnect, or the kill method |
fork() | Creates a new worker, from a master |
id | A unique id for a worker |
isConnected | Returns true if the worker is connected to its master, otherwise false |
isDead | Returns true if the worker's process is dead, otherwise false |
isMaster | Returns true if the current process is master, otherwise false |
isWorker | Returns true if the current process is worker, otherwise false |
kill() | Kills the current worker |
process | Returns the global Child Process |
schedulingPolicy | Sets or gets the schedulingPolicy |
send() | sends a message to a master or a worker |
settings | Returns an object containing the cluster's settings |
setupMaster() | Changes the settings of a cluster |
worker | Returns the current worker object |
workers | Returns all workers of a master |