-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
51 lines (45 loc) · 1.62 KB
/
index.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
const grpc = require('@grpc/grpc-js');
require('dotenv').config();
const fs = require('fs');
const cluster = require('cluster');
const os = require('os');
const rootCert = fs.readFileSync('./certs/ca.crt');
const certChain = fs.readFileSync('./certs/server.crt');
const privateKey = fs.readFileSync('./certs/server.key');
const db_status = require('./microservices/mysql-connect');
const redisDB = require('./microservices/redis-connect');
const serverCredentials = grpc.ServerCredentials.createSsl(rootCert, [{
cert_chain: certChain,
private_key: privateKey
}], true);
const numCPUs = os.cpus().length;
const productService = require('./services/product.service');
const productServiceDefinition = require('./protos/product_grpc_pb');
function startServer() {
const server = new grpc.Server();
server.addService(productServiceDefinition.ProductServiceService, {...productService.authenticated});
server.bindAsync(process.env.HOST + ':' + process.env.PORT, serverCredentials, (error, port) => {
if (error) {
console.error(`Server binding error: ${error.message}`);
return;
}
console.log(`Server running on port ${port}`);
});
}
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`);
// Optionally, you can fork a new worker here
cluster.fork();
});
} else {
// Workers can share any TCP connection
// In this case, it is a gRPC server
startServer();
console.log(`Worker ${process.pid} started`);
}