Node.jsクラスタープロセスモジュール
例
コードを3回実行します。最初はマスターとして、次にワーカーとして実行します。
var cluster = require('cluster');
if (cluster.isWorker) {
console.log('I am a worker');
} else {
console.log('I am a
master');
cluster.fork();
cluster.fork();
}
定義と使用法
クラスタモジュールは、同時に実行され、同じサーバーポートを共有する子プロセスを作成する方法を提供します。
Node.jsはシングルスレッドプログラミングを実行します。これはメモリ効率が非常に高いですが、コンピューターのマルチコアシステムを利用するために、クラスターモジュールを使用すると、それぞれが独自のシングルスレッドで実行される子プロセスを簡単に作成して負荷を処理できます。
構文
アプリケーションにクラスターモジュールを含めるための構文:
var cluster = require('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 |