nodeJS 是一门单线程!异步!非阻塞语言!
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log('[master] ' + "start master...");
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('listening', function (worker, address) {
console.log('[master] ' + 'listening: worker' + worker.id + ',pid:' + worker.process.pid + ', Address:' + address.address + ":" + address.port);
});
cluster.on('exit', function () {
console.log('A worker process died, restarting...');
cluster.fork();
});
} else if (cluster.isWorker) {
console.log('[worker] ' + "start worker ..." + cluster.worker.id);
http.createServer(function (req, res) {
console.log('worker' + cluster.worker.id);
let data = []
req.on('data', chunk => {
data.push(chunk.toString())
})
req.on('end', () => {
console.log(data)
})
try {
if (req.url === '/') {
res.end('worker' + cluster.worker.id + ',PID:' + process.pid);
} else if (req.url === '/test') {
a(111)
} else if (req.url === '/a') {
res.end(" xxxxx");
}
} catch (e) {
res.end(" error");
}
})
}