|
@@ -0,0 +1,57 @@
|
|
|
+import cluster from "cluster";
|
|
|
+import os from "os";
|
|
|
+import { setupMaster, setupWorker } from "@socket.io/sticky";
|
|
|
+import { createAdapter, setupPrimary } from "@socket.io/cluster-adapter";
|
|
|
+import { io } from "./io.js";
|
|
|
+import http from "http";
|
|
|
+import { Server } from "socket.io";
|
|
|
+import { controller } from "../controller/index.js";
|
|
|
+
|
|
|
+const numCPUs = os.cpus().length;
|
|
|
+
|
|
|
+export class CoreCluster {
|
|
|
+ constructor(port) {
|
|
|
+ this.port = port;
|
|
|
+ this.attachThead();
|
|
|
+ }
|
|
|
+ attachThead() {
|
|
|
+ if (cluster.isMaster) {
|
|
|
+ console.log("Total Number of Cores: %o", numCPUs);
|
|
|
+ console.log(`Master ${process.pid} is running`);
|
|
|
+
|
|
|
+ // setup sticky sessions
|
|
|
+ const httpServer = http.createServer();
|
|
|
+ setupMaster(httpServer, {
|
|
|
+ loadBalancingMethod: "least-connection",
|
|
|
+ });
|
|
|
+
|
|
|
+ setupPrimary();
|
|
|
+
|
|
|
+ cluster.setupPrimary({
|
|
|
+ serialization: "advanced",
|
|
|
+ });
|
|
|
+
|
|
|
+ httpServer.listen(this.port);
|
|
|
+ console.log(`server is running on port ${this.port}`);
|
|
|
+
|
|
|
+ for (let i = 0; i < numCPUs; i++) {
|
|
|
+ cluster.fork();
|
|
|
+ }
|
|
|
+ cluster.on("exit", (worker) => {
|
|
|
+ console.log(`Worker ${worker.process.pid} died`);
|
|
|
+ cluster.fork();
|
|
|
+ });
|
|
|
+ cluster.on("online", (worker) => {
|
|
|
+ console.log("Worker %o is listening", worker.process.pid);
|
|
|
+ });
|
|
|
+ } else {
|
|
|
+ console.log(`Worker ${process.pid} started`);
|
|
|
+ // use the cluster adapter
|
|
|
+ io.adapter(createAdapter());
|
|
|
+
|
|
|
+ // setup connection with the primary process
|
|
|
+ controller.run();
|
|
|
+ setupWorker(io);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|