Cluster NodeJS
import { BullQueue } from '@libs/lib.bullmq'
import cluster, { Worker } from 'cluster'
import os from 'os'
const clusterWorker = (fn: () => void) => {
if (cluster.isPrimary) {
const totalCore: number = os.cpus().length
const totalWorker: any[] = []
// calling worker
for (let i = 0; i < totalCore; i++) {
cluster.fork()
}
// extract worker data
for (let j in cluster.workers) {
totalWorker.push(j as any)
}
// tell me worker for kill worker is worker dead
totalWorker.forEach(async (worker: number): Promise<void> => {
await cluster.workers[worker].send({
from: 'isPrimary',
type: 'SIGKILL',
message: 'cleanup is worker dead and change to new worker'
})
})
// list status worker already running
cluster.on('online', (worker: Worker) => {
if (worker.isConnected()) {
console.info(`worker: ${worker.id} is online - pid: ${worker.process.pid}`)
}
})
// create new worker if worker is dead
cluster.on('exit', (worker: Worker, _code: number, _signal: string) => {
if (worker.isDead()) {
console.info(`worker: ${worker.id} is dead - pid: ${worker.process.pid}`)
}
cluster.fork()
})
} else {
if (cluster.isWorker) {
process.send('ok captain', (err: Error) => {
if (!err) fn()
})
}
}
}
// result value
const queueProcess = async () => {
setTimeout(() => {
console.log("hello wordl")
}, 2000)
}
clusterWorker(queueProcess)
Restu Wahyu Saputra