-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
55 lines (44 loc) · 1.48 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
require("dotenv").config();
const cluster = require("cluster");
const os = require("os");
const { setupMaster } = require("@socket.io/sticky");
const { setupPrimary } = require("@socket.io/cluster-adapter");
const http = require("http");
const httpServer = http.createServer();
// Setup sticky sessions with load balancing
setupMaster(httpServer, {
loadBalancingMethod: "least-connection",
});
// Setup connections between workers
setupPrimary();
const maxWorkers = os.cpus().length;
// Use Round Robin scheduling for worker distribution
cluster.schedulingPolicy = cluster.SCHED_RR;
cluster.setupPrimary({
exec: "./src/handlers/worker.js",
args: ["--use", "https"],
});
// Fork workers
function forkWorkers(count) {
for (let i = 0; i < count; i++) {
if (Object.values(cluster.workers).length < maxWorkers) {
const worker = cluster.fork();
console.log(`Worker forked: ${worker.process.pid}`);
}
}
}
// Fork half of the available CPU cores
forkWorkers(Math.floor(maxWorkers / 2));
// Handle worker exit
cluster.on("exit", (worker, code, signal) => {
console.warn(`Worker died: ${worker.process.pid}, Code: ${code}, Signal: ${signal}`);
if (Object.values(cluster.workers).length < 1) {
console.log("No workers left, forking a new one...");
forkWorkers(1);
}
});
// Handle messages from workers
cluster.on("message", (worker, message) => {
if (message == "REQ[Fork]")
forkWorkers(1); // Fork a new worker on message received
});