Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Nodejs-cluster module

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "how to use the Nodejs-cluster module", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use the Nodejs-cluster module" this article.

Basic usage

The Node.js default single process runs, up to 512MB memory for 32-bit systems and up to 1GB memory for 64-bit systems. For multicore CPU computers, this is inefficient because only one core is running and the other cores are idle. Cluster module is proposed to solve this problem.

The cluster module allows the establishment of a main process and several worker processes, which monitor and coordinate the operation of the worker process. Worker uses inter-process communication to exchange messages, cluster module has a load balancer, and Round-robin algorithm is used to coordinate the load of each worker process. At run time, all newly established links are completed by the main process, which then assigns the TCP connection to the specified worker process.

Var cluster = require ('cluster'); var os = require (' os'); if (cluster.isMaster) {for (var I = 0, n = os.cpus (). Length; I < n; I + = 1) {cluster.fork ();}} else {http.createServer (function (req, res) {res.writeHead (200); res.end ("hello world\ n");}) .requests (8000);}

The above code first determines whether the current process is the main process (cluster.isMaster). If so, create several new worker processes according to the core number of CPU; if not, indicate that the current process is a worker process, then start a server program in the process.

The drawback of the above code is that once the work process dies, the main process cannot know. To solve this problem, you can deploy listeners for online events and exit events in the main process.

Var cluster = require ('cluster'); if (cluster.isMaster) {var numWorkers = require (' os'). Cpus (). Length; console.log ('Master cluster setting up' + numWorkers + 'workers...'); for (var I = 0; I < numWorkers; iTunes +) {cluster.fork ();} cluster.on (' online', function (worker) {console.log ('Worker' + worker.process.pid +'is online');}) Cluster.on ('exit', function (worker, code, signal) {console.log (' Worker'+ worker.process.pid + 'died with code:' + code +', and signal:'+ signal); console.log ('Starting a new worker'); cluster.fork ();});}

In the above code, once the main process listens to the exit event of the worker process, it restarts a worker process. Once the worker process starts successfully and is ready to run, the online event is issued.

Worker object

The worker object is the return value of cluster.fork (), which represents a worker process.

Its properties and methods are as follows.

(1) worker.id

Worker.id returns the unique process number of the current worker. This number is also the index value in cluster.workers that points to the current process.

(2) worker.process

All worker processes are generated with child_process.fork (). The object returned by child_process.fork () is saved in the worker.process. Through this property, you can get the process object in which the worker is located.

(3) worker.send ()

This method is used to send information to the child process in the main process.

If (cluster.isMaster) {var worker = cluster.fork (); worker.send ('hi there');} else if (cluster.isWorker) {process.on ('message', function (msg) {process.send (msg);});}

The purpose of the above code is that the worker process echoes every message sent by the main process.

In the worker process, to send messages to the main process, use process.send (message); to listen for messages sent by the main process, use the following code.

Process.on ('message', function (message) {console.log (message);})

The message sent can be either a string or a JSON object. Here is an example of sending a JSON object.

Worker.send ({type: 'task 1targets, from:' master', data: {/ / the data that you want to transfer}}); cluster.workers object

This object is available only to the main process and contains all worker processes. The key value of each member is a worker process object, and the key name is the worker.id property of the worker process.

Socket.on ('data', function (id) {var worker = cluster.workers [id];}); attributes and methods of cluster module

IsMaster,isWorker

The isMaster property returns a Boolean value indicating whether the current process is the main process. This attribute is determined by process.env.NODE_UNIQUE_ID, and if process.env.NODE_UNIQUE_ID is undefined, it means that the process is the main process.

The isWorker property returns a Boolean value indicating whether the current process is a work process. It is the opposite of the value of the isMaster property.

Fork ()

The fork method is used to create a new worker process that replicates the main process in both contexts. Only the main process can call this method.

This method returns a worker object.

Kill ()

The kill method is used to terminate the worker process. It can accept a parameter that represents the system signal.

If it is currently the main process, the contact with the worker.process is terminated and the system signaling method is sent to the worker process. If it is currently a worker process, it terminates communication with the main process, then exits and returns 0.

In previous versions, this method was also called worker.destroy ().

Listening event

After the worker process calls the listening method, the "listening" event is passed to the process's server and then to the main process.

The callback function of this event takes two parameters, one is the current worker object, and the other is the address object, which contains information such as URL, port, address type (IPv4, IPv6, Unix socket, UDP), and so on. This is useful for Node applications that serve multiple URLs.

Restart the Node service without interruption

The restart service needs to be shut down and then started. Using the cluster module, you can start a worker process first, and then shut down all the original work processes. This makes it possible to restart the Node service without interruption.

First, the main process sends a restart signal to the worker process.

Workers [wid] .send ({type: 'shutdown', from:' master'})

The worker process listens for message events and exits as soon as it discovers that the content is shutdown.

Process.on ('message', function (message) {if (message.type =' shutdown') {process.exit (0);}})

Here is a function that shuts down all worker processes.

Function restartWorkers () {var wid, workerIds = []; for (wid in cluster.workers) {workerIds.push (wid);} workerIds.forEach (function (wid) {cluster.workers[ wid] .send ({text: 'shutdown', from:' master'}); setTimeout (function () {if (cluster.workers[ wid]) {cluster.workers[ wid] .kill ('SIGKILL') }, 5000););}; PM2 module

The PM2 module is a wrapper layer for cluster modules. Its function is to abstract the cluster module as much as possible, allowing users to deploy multi-process Node applications as if they were using a single process.

/ / app.jsvar http = require ('http'); http.createServer (function (req, res) {res.writeHead (200); res.end ("hello world");}) .salary (8080)

Start this code from the command line with PM2

$pm2 start app.js-I 4

The I parameter of the above code tells PM2 that this code should be started in cluster_mode and that the number of new worker processes is 4. If the value of the I parameter is 0, then the current machine has several CPU cores, and PM2 will start several worker processes.

If a worker process dies for some reason, the worker process will be restarted immediately.

# restart all worker processes $pm2 reload all

Each worker process has an id, and you can use the following command to view the details of a single worker process.

$pm2 show

When you shut down the worker process, you can deploy the following code to have the worker process listen for shutdown messages. Once you receive this message, finish the clean-up and then close it.

Process.on ('message', function (msg) {if (msg =' shutdown') {close_all_connections (); delete_logs (); server.close (); process.exit (0);}}); these are all the contents of the article "how to use the Nodejs-cluster module". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report