当前位置:网站首页>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/
边栏推荐
- How important is 5g dual card dual access?
- Query the size of each table in the database
- High availability solution practice of mongodb advanced applications (4)
- Drawing black technology - easy to build a "real twin" 2D scene
- 7、VLAN-Trunk
- Three functional forms of intelligent switch
- 股票网上开户及开户流程怎样?在线开户安全么?
- FPN characteristic pyramid network
- Redis cluster operation method
- [go] calling Alipay to scan code for payment in a sandbox environment
猜你喜欢

【网络通信 -- WebRTC】WebRTC 源码分析 -- PacingController 相关知识点补充

MySQL transaction and its characteristics and locking mechanism

qYKVEtqdDg
![[go]沙盒环境下调用支付宝扫码支付](/img/d4/c6d72a697bc08f69f11121a15109b3.png)
[go]沙盒环境下调用支付宝扫码支付

JSON - learning notes (message converter, etc.)

Troubleshooting of datanode entering stale status

Practice sharing of chaos engineering in stability management of cloud native Middleware

MySQL事务及其特性与锁机制

Wechat applet: time selector for the estimated arrival date of the hotel

Hands on data analysis unit 2 section 4 data visualization
随机推荐
Intelligent supply chain collaborative management solution for logistics industry
C. Add One--Divide by Zero 2021 and Codeforces Round #714 (Div. 2)
Hapoxy cluster service setup
hands-on-data-analysis 第二单元 第四节数据可视化
[go]沙盒环境下调用支付宝扫码支付
Troubleshooting of datanode entering stale status
PostgreSQL series articles -- the world's most advanced open source relational database
Also using copy and paste to create test data, try the data assistant!
Explanation of the principle and code implementation analysis of rainbow docking istio
美团三面:聊聊你理解的Redis主从复制原理?
C # connection to database
Redis ubuntu18.04.6 intranet deployment
mysql-选择使用Repeatable read的原因
Interpretation of eventbus source code
Analysis of object class structure in Nanny level teaching (common class) [source code attached]
qYKVEtqdDg
Spdlog logging example - create a logger using sink
History of storage technology: from tape to hardware liquefaction
AMQP protocol
12. Manage network environment