[Node.js] Child Process with fork() to handle heavy calculation process

本文介绍了一种使用Node.js的'child_process'模块中的fork方法来避免API端点处理长时间运行任务时导致的服务器阻塞。通过将耗时计算任务分离到子进程中,可以确保主线程响应不受影响,提高服务器处理并发请求的能力。

When build server, if we have a API endpoint requires some heavy calculation process, it will block the whole world. In this post, we will see how to use 'child_process' fork() to solve the problem;

 

Let's see the blocking code example:

const http = require('http');

const longComputation = () => {
    let sum = 0;
    for (let i = 0; i < 1e9; i++) {
        sum += i;
    }
    return sum;
}

const server = http.createServer();

server.on('request', (req, res) => {
    if (req.url === '/compute') {
        const sum = longComputation();
        return res.end(`Sum is ${sum}`);
    } else {
        res.end('Ok');
    }
})

When we request '/compute' API endpoint, because of 'longCompute', it blocks the world, no other request can go thought.

curl localhost:3000/compute

 

Let's see how to fix it:

1. We will create a compute.js to hold the 'longCompute' function and also listen to the 'message' event on the global:

// Compute.js
const longComputation = () => {
    let sum = 0;
    for (let i = 0; i < 1e9; i++) {
        sum += i;
    }
    return sum;
}

// listen the mssage event on the global
// then do the computation
process.on('message', (msg) => {
    const sum = longComputation();
    process.send(sum);
})

 

2. In server.js, instead of calling 'longCompute' directly, we fork the compute.js;

Send signal to tell the compute file to start doing the job, then we also need to listen to the event come back after computation is done.

// start processing
compute.send('start');
// listen to the message
compute.on('message', sum => {
    res.end(`Sum is ${sum}`);
});

 

Full code for server.js

const http = require('http');
const {fork} = require('child_process');

const server = http.createServer();

server.on('request', (req, res) => {
    if (req.url === '/compute') {
        const compute = fork('compute.js');
        // start processing
        compute.send('start');
        // listen to the message
        compute.on('message', sum => {
            res.end(`Sum is ${sum}`);
        });
    } else {
        res.end('Ok');
    }
});
server.listen(3000)

 

转载于:https://www.cnblogs.com/Answer1215/p/10498591.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值