在node.js集群之间划分快速路由

时间:2018-10-30 10:31:59

标签: javascript node.js cluster-computing

我对Node.JS / Cluster / Express很陌生。我与所有这些员工一起工作,并尝试执行一项特定任务。我想让每条路线(例如,现在我有用户)在单独的工作程序中运行。

现在,我所有的路由都在一个工作进程中运行,并且它们与服务(不同子进程中的服务)进行通信。

const cluster = require('cluster');
const express = require('express');
const bodyParser = require('body-parser');
const childProcess = require('child_process');
const morgan = require('morgan');
const numCPUs = require('os').cpus().length;

const usersRoute = require('./routes/users');

const app = express();
const PORT = 8080;

if (cluster.isMaster) {
const usersWorker = childProcess.fork('./services/users');

for (let i = 0; i < numCPUs; i ++) {
    let worker = cluster.fork().process;
    console.log(`Worker with ${worker.pid} started...`);
}

cluster.on('disconnect', (worker) => {
    console.error(`Worker ${worker.id} died...`);
    let newWorker = cluster.fork().process;
    console.log(`New worker ${newWorker.pid} created...`);
});

cluster.on('online', (worker) => {
    console.log(`Worker ${worker.id} is online...`);

    worker.on('message', (message) => {
        switch (message.type) {
            case 'users':
                usersWorker.send(message);
                usersWorker.on('message', (msg) => {
                    worker.send(msg);
                });
        }
    });
});
} else {
app.use(morgan('tiny'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use('/users', usersRoute);
app.listen(PORT, () => console.log(`I'm running on port ${PORT}. You are welcome!`));
}

和简单的路线:

const express = require('express');

const router = express.Router();

router.get('/', (req, res) => {
    console.log(`Users worker ${process.pid}`)
    process.send({
        type: 'users',
        body: 'Hello from users'
    });
    process.on('message', (message) => {
        console.log(message);
        return res.json(message);
    });
});

module.exports = router;

所以我的用户srv看起来像这样,没什么特别的:

process.on('message', (message) => {
    console.log(`Worker ${process.pid} is here...`);
    const obj = {};
    obj.route = message;
    obj.service = process.pid;
    console.log('Gonna send this');
    console.log(obj);
    process.send(obj);
});

我有一个选择,如何将特定的路线附加到特定的工作人员上?

谢谢!

0 个答案:

没有答案