当前位置:网站首页>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/
边栏推荐
- The mail function is normal locally, and the ECS reports an error
- History of storage technology: from tape to hardware liquefaction
- 解答03:Smith圆为什么能“上感下容 左串右并”?
- How to make a shirt certificate
- Lighthouse open source application practice: o2oa
- Hands on data analysis unit 2 section 4 data visualization
- How to open an account through online stock? Is online account opening safe?
- mysql-选择使用Repeatable read的原因
- 如何通过线上股票开户?在线开户安全么?
- The principle of MySQL index algorithm and the use of common indexes
猜你喜欢

FPN characteristic pyramid network

Meituan Sanmian: how do you understand the principle of redis master-slave replication?

微信小程序:酒店预计到店日期的时间选择器

【网络通信 -- WebRTC】WebRTC 源码分析 -- 接收端带宽估计
![[network communication -- webrtc] analysis of webrtc source code -- supplement of pacingcontroller related knowledge points](/img/18/dda0c7fa33ee6cdf2bbb2f85099940.png)
[network communication -- webrtc] analysis of webrtc source code -- supplement of pacingcontroller related knowledge points
![[mae]masked autoencoders mask self encoder](/img/08/5ab2b0d5b81c723919046699bb6f6d.png)
[mae]masked autoencoders mask self encoder
![[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

How important is 5g dual card dual access?

12 initialization of beautifulsoup class

10分钟后性能测试瓶颈调优!想进大厂这个必须会
随机推荐
Li Kou daily question - day 25 -495 Timo attack
Get first and last days by year
Revil - blackmail Virus Emergency Response
13. IP address and subnet partitioning (VLSM)
一文入门智能开关的3种功能形态
Listen attentively and give back sincerely! Pay tribute to the best product people!
January 5, 2022: there are four kinds of rhythms: AABB, ABAB and ABB
How to open an account through online stock? Is online account opening safe?
JSON - learning notes (message converter, etc.)
Nanny level teaching! Take you to play with time complexity and space complexity!
Tencent three sides: how to duplicate 4billion QQ numbers?
Similarities and differences between Chinese and American electronic signature SaaS
FPN characteristic pyramid network
Date to localdatetime
浅析3种电池容量监测方案
Analysis of object class structure in Nanny level teaching (common class) [source code attached]
Redis cluster operation method
Easyplayer mobile terminal plays webrtc protocol for a long time. Pressing the play page cannot close the "about us" page
C. Set or Decrease-Educational Codeforces Round 120 (Rated for Div. 2)
Innovative technology leader! Huawei cloud gaussdb won the 2022 authoritative award in the field of cloud native database