Modul Kluster membenarkan Node.js memanfaatkan sistem berbilang teras, meningkatkan prestasi apl. Mari kita terokai cara menggunakannya dengan berkesan.
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { console.log(`Master ${process.pid} is running`); // Fork workers for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection http.createServer((req, res) => { res.writeHead(200); res.end('Hello World\n'); }).listen(8000); console.log(`Worker ${process.pid} started`); }
Node.js mengendalikan pengimbangan beban secara automatik menggunakan pendekatan round-robin.
if (cluster.isMaster) { const worker = cluster.fork(); worker.send('Hi there'); } else { process.on('message', (msg) => { console.log('Message from master:', msg); }); }
if (cluster.isMaster) { cluster.on('exit', (worker, code, signal) => { if (!worker.exitedAfterDisconnect) { console.log('Worker crashed. Starting a new worker'); cluster.fork(); } }); process.on('SIGUSR2', () => { const workers = Object.values(cluster.workers); const restartWorker = (workerIndex) => { const worker = workers[workerIndex]; if (!worker) return; worker.on('exit', () => { if (!worker.exitedAfterDisconnect) return; console.log(`Exited process ${worker.process.pid}`); cluster.fork().on('listening', () => { restartWorker(workerIndex + 1); }); }); worker.disconnect(); }; restartWorker(0); }); }
Modul kluster berkuasa untuk penskalaan mendatar, tetapi gunakan dengan bijak. Sentiasa membuat profil untuk memastikan ia menyelesaikan keperluan prestasi khusus anda.
Sekian?
Atas ialah kandungan terperinci Menskalakan Node.js dengan Modul Kluster. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!