在Ubuntu上使用Node.js實現集群模式,可以通過Node.js內置的cluster
模塊來實現。cluster
模塊允許你創建多個工作進程(worker processes),這些進程共享同一個服務器端口,從而提高應用程序的性能和可靠性。
以下是一個簡單的示例,演示如何在Ubuntu上使用Node.js的cluster
模塊實現集群模式:
sudo apt update
sudo apt install nodejs
sudo apt install npm
cluster-app.js
的文件,并添加以下代碼: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
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
這個示例中,我們首先檢查當前進程是否是主進程(master)。如果是主進程,我們將創建與CPU核心數相同的工作進程(workers)。每個工作進程都將運行相同的HTTP服務器,監聽8000端口。
node cluster-app.js
http://your-ubuntu-ip:8000
,你應該能看到"hello world"的響應。由于我們使用了cluster
模塊,請求將在多個工作進程之間進行負載均衡。這就是在Ubuntu上使用Node.js實現集群模式的基本方法。你可以根據實際需求調整代碼,例如添加負載均衡策略、錯誤處理等。