forked from tapd8/apig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_cluster.js
70 lines (64 loc) · 1.63 KB
/
app_cluster.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
const cluster = require('cluster');
const log = require('./dist').log.app;
const Conf = require('conf');
const config = new Conf();
let appWorker = null;
/**
* 工作进程
*/
const workerRun = function () {
// const appConfig = require('./config');
const application = require('./dist');
// const report = require('./report');
// Run the application
const configm = {
rest: {
port: config.get('port') || +process.env.PORT || 3030,
host: config.get('host') || process.env.HOST || 'localhost',
openApiSpec: {
// useful when used with OASGraph to locate your application
setServersFromRequest: true,
},
},
};
application.main(configm, (result) => {
if (result && typeof process.send === 'function')
process.send({
type: 'started',
});
}).catch(err => {
log.error('Cannot start the application.', err);
process.exit(1);
});
},
/**
* 主进程
*/
startWorker = function () {
// 监听父进程消息,接收到重启指令后,重启app
let worker = cluster.fork();
worker.on('message', (event) => {
log.debug(`which pid? app_cluster.js:43: ${process.pid} and event: ${JSON.stringify(event)}`);
if (event && event.type === 'started') {
if (appWorker) {
appWorker.kill();
}
appWorker = worker;
process.send({
type: 'status',
data: 'running'
});
}
});
};
if (cluster.isMaster) {
log.debug(`master process.pid@app_cluster.js:53: ${process.pid}`);
startWorker();
process.on('message', (event) => {
if (event && event.type === 'restart')
startWorker();
})
} else {
log.debug(`slave process.pid@app_cluster.js:60: ${process.pid}`);
workerRun();
}