-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkerPool.js
More file actions
57 lines (46 loc) · 1.54 KB
/
workerPool.js
File metadata and controls
57 lines (46 loc) · 1.54 KB
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
import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// 兼容 ESM 下的 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
class WorkerPool {
constructor() {
this.workers = [];
}
startWorker(type, port) {
const scriptPath = path.join(__dirname, 'server', `${type}.js`);
// 启动子进程
const proc = spawn(process.execPath, [scriptPath], {
env: { ...process.env, PORT: port },
stdio: ['ignore', 'pipe', 'pipe']
});
proc.stdout.on('data', data => console.log(`[${type}](${port}): ${data.toString().trim()}`));
proc.stderr.on('data', data => console.error(`[${type}](${port}) ERR: ${data.toString().trim()}`));
// 错误事件监听
proc.on('error', err => {
console.error(`❌ Failed to spawn ${type} worker (${port}):`, err);
});
const worker = { type, port, process: proc, host: null, healthy: true, requests: 0 };
this.workers.push(worker);
return worker;
}
// register external (already running) worker
registerExternal(type, host, port) {
const w = { type, host, port, process: null, healthy: true, requests: 0 };
this.workers.push(w);
return w;
}
stopWorker(worker) {
if (worker.process) {
console.log(`Stopping worker ${worker.type} (${worker.port})`);
worker.process.kill();
}
this.workers = this.workers.filter(w => w !== worker);
}
list() {
return this.workers;
}
}
export default WorkerPool;