lead

A Node.js application can only be used in one thread. More recently, to take full advantage of multi-core cpus, node.js has provided a cluster module that allows different Node.js applications to run in multiple child processes.

Use the fork method to create the worker object

In a Cluster module, you can fork multiple child processes, create an instance of a Node.js application in each child process, and run a module file in that application

cluster.fork([env]
Copy the code
  • Env: an object used to specify environment variables for child processes in the form of key name/key value.

The fork method returns an implicitly created worker object that represents the Node.js application instance object running in the child process opened with the fork method.

In addition, in the cluster module, an isMaster attribute and an isWorker attribute are provided respectively, and the attribute values of these two attributes are both a Boolean value.

  • The isMaster property is true if the instance object of the Node.js application is running in the main process.
  • The isWorker property is true if the instance object of the Node.js application is running in a child process.

In the cluster module, worker objects running in all child processes can be obtained through the value of workers attribute

// Iterate over the workers attribute valuesfor (var index in cluster.workers) {
    console.log(cluster.workers[index]);
}
Copy the code

In the Node.js application running in the child process, you can obtain the Node.js application instance object running in the current child process by using the cluster.worker attribute value, and you can also obtain the ID of the cluster.worker object by using the cluster.worker.id attribute value

if (cluster.isMaster) {
    cluster.fork();
}
else if (cluster.isWorker) {
    console.log('I am worker #' + cluster.worker.id);
}
Copy the code

In node.js applications where child processes are running, the current child process can be obtained from the cluster.worker.process property value,

if (cluster.isWorker) {
    worker.process.stdout.write('hello');
}
Copy the code

Fork method instance

var cluster = require('cluster');
var http = require('http');
if (cluster.isMaster) {
    cluster.fork();
    console.log('This code is run in the main process. ');
}
else {
    http.createServer(function(req, res) {
        if(req.url! = ="/favicon.ico"){
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write('<head><meta charset="utf-8"/></head>');
            res.end('hello \ n');
            console.log("This code is run in a child process.");
        }
    }).listen(1337);
}
Copy the code

When fork is used to open a child process, the fork event is also triggered. You can specify the processing to be performed when the child process is opened by listening for the event and specifying the event callback function

cluster.on('fork'.function(worker) {// event callback});Copy the code

After the fork method is used to open a new child process used to run the Node.js application, the application sends a feedback message to the main process. When the main process receives the feedback, the online event is triggered. You can specify what processing to do when the Node.js application in the child process sends feedback to the main process by listening on the event and specifying the event callback function

cluster.on('online'.function(worker) {// event callback});Copy the code

In the online event callback function, use a parameter whose value is the worker object returned after opening the child process using the fork method.

When the server’s LISTEN method is called in the Node.js application running in the child process, the server starts listening for the specified address and port, and fires the Listening event.

cluster.on('listening'.function(worker,address) {// event callback});Copy the code
  • Worker: is the worker object returned after opening the child process using the fork method,
  • Address: is an object that has attributes and attribute values as shown below.
    • Address: Property value is the address listened by the server in the child process.
    • Port: Property value is the port number listened by the server in the child process.
    • AddressType: the attribute value is the addressType that the server listens to. If the value is 4, the IP address is an IPv4 address. If the value of attribute is 6, it indicates that the address is an IPv6 address.

setupMaster

Node.js applications in child processes run the main module file in the currently running Node.js application by default. You can use the setupMaster method to modify the module file running in child processes or modify other default behaviors of Node.js applications running in child processes.

cluster.setupMaster([settings])
Copy the code
  • Settings: Uses an optional parameter in the setupMaster method. The parameter value is an object used to set the various default behaviors of the Node.js application running in the child process, and the properties and values that can be used in this object
    • Exec: Property values are the full path and file name of the running template file in the child process. The default property values are the full path file name of the main module file in the currently running Node.js application.
    • Args: The property value is an array containing all the parameters needed to run node.js applications in the child process. The default property value is an array containing all the parameters used by the currently running Node.js applications.
    • Silent: The attribute value is a Boolean value. When the property value is false, the child process object shares standard input/output with the main process object. When the property value is true, the child process object does not share standard input/output with the main process object. The default property value is false.

Methods and events of the Worker object

After the fork method is used to start a new child process for running node.js application, the application will send a feedback message to the main process. When the main process receives the feedback message, the fork method will trigger the online event that returns the worker object. You can specify the processing to be performed when the Node.js application in the child process sends feedback to the main process by listening on the event and specifying the event callback function with no arguments.

var cluster = require('cluster');
var http = require('http');
if (cluster.isMaster) {
var worker=cluster.fork();
    console.log('This code is run in the main process. ');
    worker.on('online'.function() {
        console.log("Child process received"+worker.id.toString()+"Feedback.");
    });
}
else {
    http.createServer(function(req, res) {
        if(req.url! = ="/favicon.ico"){
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write('<head><meta charset="utf-8"/></head>');
            res.end('hello \ n');
            console.log("This code is run in a child process.");
        }
    }).listen(1337);
}

Copy the code

When the server’s LISTEN method is called in the Node.js application running in the child process, the server starts to listen on the specified address and port, and triggers the listening event of the worker object used to start the child process. You can specify what processing to perform when the server running in the child process starts listening by listening on the event and specifying the event callback function

worker.on('listening'.function(address) {// event callback function code omitted});Copy the code
  • The address: parameter value is an object that has properties and property values as shown below.
    • Address: Property value is the address listened by the server in the child process.
    • Port: Property value is the port number listened by the server in the child process.
    • AddressType: the attribute value is the addressType that the server listens to. If the value is 4, the IP address is an IPv4 address. If the value of attribute is 6, it indicates that the address is an IPv6 address.

When fork is used to start the child process, the send method of worker object returned by fork can be used to send messages to the child process in the main process, and the send method of process object can also be used to send messages to the main process in the child process. In Node.js, the two methods are actually the same method. This method can be used as follows.

Worker.send (message,[sendHandle]) // Sends a message in the main process to the child process process.send(message,[sendHandle]) // Sends a message in the child process to the main processCopy the code
  • Message: Specifies the message to be sent.
  • SendHandle: a callback function that is executed when a message is received. It can also be a server object or a socket port object that is shared between the main process and child processes.

Force the child process to close

worker.kill([signal])
Copy the code