Mô-đun quy trình cụm Node.js
Thí dụ
Chạy mã ba lần, lần đầu tiên là với tư cách chủ, sau đó là công nhân:
var cluster = require('cluster');
if (cluster.isWorker) {
console.log('I am a worker');
} else {
console.log('I am a
master');
cluster.fork();
cluster.fork();
}
Định nghĩa và Cách sử dụng
Mô-đun cụm cung cấp một cách tạo các quy trình con chạy đồng thời và chia sẻ cùng một cổng máy chủ.
Node.js chạy chương trình đơn luồng, rất tiết kiệm bộ nhớ, nhưng để tận dụng các hệ thống đa lõi của máy tính, mô-đun Cluster cho phép bạn dễ dàng tạo các quy trình con mà mỗi quy trình chạy trên một luồng riêng của chúng, để xử lý tải.
Cú pháp
Cú pháp để bao gồm mô-đun cụm trong ứng dụng của bạn:
var cluster = require('cluster');
Thuộc tính và phương thức cụm
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 |