-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
76 lines (63 loc) · 1.75 KB
/
server.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const mongoose = require("mongoose");
const expressServer = require("./src/config/express");
const cluster = require("cluster");
const OS = require("os");
const { databaseUrl } = require("./src/app/Constants/database");
const PORT = process.env.PORT || 8080;
class App {
constructor(workers, autoScale = true) {
this.buildCluster(workers, autoScale);
}
database = () => {
mongoose.connect(databaseUrl, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on("connected", () => {
console.log("Connected Database");
});
process.on("SIGINT", () => {
mongoose.connection.close(() => {
console.log("Close database connection");
process.exit(0);
});
});
mongoose.connection.on("error", (error) => {
console.log("Connection Error: " + error);
});
};
buildCluster = (workers, autoScale) => {
if (autoScale) {
workers = this.autoScale(workers);
}
if (cluster.isMaster) {
console.log("Cluster Master Online");
for (let i = 0; i < workers; i += 1) {
console.log(`Creating instances ${workers}`);
cluster.fork();
}
cluster.on("exit", (worker) => {
console.error(`Worker ${worker.id} Offline`);
cluster.fork();
});
} else {
expressServer.listen(PORT, () => {
this.database();
console.log(`Server running on port ${PORT}`);
});
}
};
autoScale = (workersByCpu) => {
const cpus = OS.cpus().length;
const workers = cpus / workersByCpu;
return workers;
};
}
/**
* Application Start
*
* @param number number of workers
* @param boolean auto scale will use the number of workers by each CPU
*/
new App(1, false);