当前位置:网站首页>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/
边栏推荐
- Installation, configuration, désinstallation de MySQL
- Thymeleaf - learning notes
- 开户券商怎么选择?现在网上开户安全么?
- Is it cost-effective to buy a long-term financial product?
- C # connection to database
- QT当中的【QSetting和.ini配置文件】以及【创建Resources.qrc】
- 10分钟后性能测试瓶颈调优!想进大厂这个必须会
- 如何通过线上股票开户?在线开户安全么?
- 【30. 串联所有单词的子串】
- [go] calling Alipay to scan code for payment in a sandbox environment
猜你喜欢

千呼万唤,5G双卡双通到底有多重要?

Troubleshooting of datanode entering stale status

Database Experiment 2 query

数据库 实验二 查询

酒店入住时间和离店时间的日期选择

Easyplayer mobile terminal plays webrtc protocol for a long time. Pressing the play page cannot close the "about us" page

Hands on data analysis unit 2 section 4 data visualization

【30. 串联所有单词的子串】

hands-on-data-analysis 第二单元 第四节数据可视化

FPN characteristic pyramid network
随机推荐
单火线设计系列文章10:拓展应用-单火开关实现双控
C. Add One--Divide by Zero 2021 and Codeforces Round #714 (Div. 2)
Postgresql_ Optimize SQL based on execution plan
Troubleshooting of datanode entering stale status
Thymeleaf - learning notes
【网络通信 -- WebRTC】WebRTC 源码分析 -- PacingController 相关知识点补充
MySQL transaction and its characteristics and locking mechanism
[untitled] Application of laser welding in medical treatment
Illustration of mongodb cluster deployment principle (3)
千呼万唤,5G双卡双通到底有多重要?
Database Experiment 2 query
浅谈5类过零检测电路
Petitpotam – NTLM relay to ad CS
JS regular verification time test() method
MySQL的 安装、配置、卸载
Li Kou daily question - day 25 -495 Timo attack
Réponse 02: pourquoi le cercle Smith peut - il "se sentir haut et bas et se tenir à droite et à droite"?
How to open an account through online stock? Is online account opening safe?
Drawing black technology - easy to build a "real twin" 2D scene
QT当中的【QSetting和.ini配置文件】以及【创建Resources.qrc】