当前位置:网站首页>Nodejs implements multi process
Nodejs implements multi process
2022-06-23 17:54:00 【conanma】
Nodejs The main process of is single threaded , But it has a multithreaded processing scheme ( More importantly, it is a multi process solution ), That is, the main process starts different sub processes , The main process receives all requests , It will then be distributed to other different nodejs Subprocess processing .
It generally has two implementations :
- The main process listens on a port , Child processes do not listen on ports , Distribute requests to child processes through the main process ;
- The main process and sub process listen to different ports respectively , Distribute requests to child processes through the main process .
cluster Pattern
Nodejs Of cluster Pattern The first implementation is used , It uses a main thread master And multiple child threads worker, Form a cluster , Distribute requests to child threads through the main thread .cluster Realized with child_process Encapsulation , adopt fork Method to create sub processes to implement the multi process model .
cluster Use
http and cluster、process All are nodejs The built-in modules , No additional installation required
- Create a http service
// http yes nodejs Built-in module
const http = require('http')
const server = http.createServer((req, res) => {
res.write('hello http!')
res.end()
})
server.listen(3030, () => {
console.log('server is listening on http://localhost:3030')
})
// process yes node Process module of , You can get the process information from this module , And control the process
console.log(`worker ${process.pid} start`)- establish cluster In the following procedure , It will first determine whether there is a main process , without , Just create the process , It will default that the first process is the main process
- In the source code , Is to call
cluster.fork()When the method is used , Will executesetupPrimaryMethod to create the main process , It will useinitializedIs the signtrueWill determine whether it is the first time to create , If yes, create the main process , Otherwise, skip - Use
createWorkerProcessTo create child processes , This method actually useschild_processTo create a child process
const cluster = require('cluster')
// Number of child processes opened
const workerNum = 3;
// If it is the main process
if(cluster.isMaster) {
// Create child process
for(let i = 0; i < workerNum; i++) {
// adopt cluster.fork Create child process
cluster.fork()
}
// If there are child processes , Start relevant services , Three processes are used to execute http Service Demo
}else {
require('./http-server')
} The implementation process is like this : cluster Module application child_process To create child processes , Subprocesses are overwritten cluster._getServer Method , Thus in server.listen To ensure that only the main process listens to the port , The master subprocess passes IPC communicate , Secondly, the main process is different according to the platform or protocol , Apply two different modules (round_robin_handle.js and shared_handle.js) Make the request and distribute it to the child process for processing .
PM2
PM2 Is the background process manager , It is a mature application of multi process solution , Can help manage and keep applications online .
Basic use
Global installation :npm install [email protected] -g It's also very simple to use :
- Turn on (http-server.js Is the program to start ):
pm2 start http-server.js - restart ( Program ):
restart app_name - heavy load ( Configuration and procedures ):
reload app_name - stop it :
pm2 stop app_name - Delete :
pm2 delete app_name - Monitor mode :
pm2 start xx.js --watch
Load balancing :
PM2 Yes nodejs application , Load balancing can be realized automatically according to the system :pm2 start http-server.js -i max
PM2 To configure
We definitely don't want to start every time , You have to manually input a bunch of instructions , So we can use the configuration file to manage these configurations , Be careful js The file name must be xxx.config.js, I use it here. ecosystem.config.js: apps Array , You can place multiple objects , Perform different configurations for multiple files
// ecosystem.config.js
module.exports = {
apps : [{
name: "http-server", // Start process name
script: "./src/http-server.js", // Startup file
instances: 4, // Number of start processes
exec_mode: 'cluster', // Multi process and multi instance
// Set the environment configuration for different environments
// development environment , Corresponding --env Later parameters
env_development: {
NODE_ENV: "dev",
watch: true, // Development environment use true, Other settings are false
},
// Test environment
env_testing: {
NODE_ENV: "test",
watch: false, // Development environment use true, Other settings are false
},
// Production environment
env_production: {
NODE_ENV: "prod",
watch: false, // Development environment use true, Others must be set to false
},
// Log date format
log_date_format: 'YYYY-MM-DD HH:mm Z',
// Error log file , Must be set in a directory outside the project , This is for testing
error_file: '~/Desktop/logs/err.log',
// Water logging , Include console.log journal , Must be set in a directory outside the project , This is for testing
out_file: '~/Desktop/logs/info.log',
// Maximum restart data , When the application is considered continuous n From unstable restart , Restart again
max_restarts: 10,
},{
name: "express-test", // Start process name
script: "./src/express-test.js", // Startup file
instances: 4, // Number of start processes
exec_mode: 'cluster', // Multi process and multi instance
}]
} Perform configuration :pm2 start ecosystem.config.js --env dev
You can see that after startup , Pipelining and error logs are generated on the desktop :
journal
Water logging
Reference resources : Node Process modular API:http://nodejs.cn/api/process.html pm2 Official website : https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/
边栏推荐
- Bypass rights
- 美团三面:聊聊你理解的Redis主从复制原理?
- Meituan Sanmian: how do you understand the principle of redis master-slave replication?
- Wechat applet: time selector for the estimated arrival date of the hotel
- [go] calling Alipay to scan code for payment in a sandbox environment
- Easyplayer mobile terminal plays webrtc protocol for a long time. Pressing the play page cannot close the "about us" page
- Codeforces Round #620 (Div. 2)ABC
- How code 39 check bits are calculated
- How to design a seckill system?
- 解答03:Smith圆为什么能“上感下容 左串右并”?
猜你喜欢

Alien world, real presentation, how does the alien version of Pokemon go achieve?
![[qsetting and.Ini configuration files] and [create resources.qrc] in QT](/img/67/85a5e7f6ad4220600acd377248ef46.png)
[qsetting and.Ini configuration files] and [create resources.qrc] in QT

JSON - learning notes (message converter, etc.)

美团三面:聊聊你理解的Redis主从复制原理?
![[mae]masked autoencoders mask self encoder](/img/08/5ab2b0d5b81c723919046699bb6f6d.png)
[mae]masked autoencoders mask self encoder

FPN characteristic pyramid network
![[network communication -- webrtc] source code analysis of webrtc -- bandwidth estimation at the receiving end](/img/b0/97dbf3d07a4ed86d6650a58a97a5fc.png)
[network communication -- webrtc] source code analysis of webrtc -- bandwidth estimation at the receiving end

12 initialization of beautifulsoup class

Date selection of hotel check-in time and check-out time
![[untitled] Application of laser welding in medical treatment](/img/c5/9c9edf1c931dfdd995570fa20cf7fd.png)
[untitled] Application of laser welding in medical treatment
随机推荐
What is the personal finance interest rate in 2022? How do individuals choose financial products?
Hands on data analysis unit 2 section 4 data visualization
QT当中的【QSetting和.ini配置文件】以及【创建Resources.qrc】
[go] calling Alipay to scan code for payment in a sandbox environment
Hapoxy-集群服务搭建
浅析3种电池容量监测方案
Postgresql_根据执行计划优化SQL
. Net cloud native architect training camp (responsibility chain mode) -- learning notes
手机开户流程是什么?现在网上开户安全么?
bypassuac提权
Troubleshooting and modification process of easycvr interface dislocation in small screen
[qsetting and.Ini configuration files] and [create resources.qrc] in QT
解答02:Smith圆为什么能“上感下容 左串右并”?
Listen attentively and give back sincerely! Pay tribute to the best product people!
【网络通信 -- WebRTC】WebRTC 源码分析 -- PacingController 相关知识点补充
解答02:Smith圓為什麼能“上感下容 左串右並”?
Company offensive operation guide
ERP管理系统的重要性
解答03:Smith圆为什么能“上感下容 左串右并”?
How to open an account through online stock? Is online account opening safe?