使用集群模块处理SIGTERM

时间:2017-12-05 10:46:34

标签: node.js

您在哪里可以找到使用群集模块时信号处理的源代码?我想处理一个SIGTERM,以便我可以优雅地#34;关闭http服务器,但主进程收到此信号后,http服务器就会停止侦听。

"终止" handler(当SIGTERM或SIGINT时调用此函数)

function handleTermination(httpServer?: http.Server) {
    if (Store.receive<symbol, boolean>(STORE_KEYS.isTerminating)) {
        return
    }

    Store.store<symbol, boolean>(STORE_KEYS.isTerminating, true)

    if (httpServer) {
        if (!httpServer.listening || isDevelopment) {
            closeAll()
            process.exit(0)
            return
        }

        setTimeout(() => {
            if (process.env.GRACEFUL_SHUTDOWN !== undefined) {
                gracefulCloseSockets()
            }

            httpServer.close(endProcess)
        }, 5000)
    } else {
        endProcess()
    }
}

示例路由器处理程序

function timerHandler(_req: RequestObject, respond: ResponseHandler) {
    setTimeout(() => respond('ok'), 2000)
}

2 个答案:

答案 0 :(得分:0)

process.on(“exit”,cb)或process.on(“beforeExit”,cb)怎么样?

答案 1 :(得分:0)

我已经解决了我的问题。这是解决我问题的代码。

<强> master.js

function close(callback) {
  if (!cluster.isMaster) {
    return
  }

  const promiseArray = []
  const workerIds = Object.keys(cluster.workers)

  for (const workerId of workerIds) {
    const worker = cluster.workers[workerId]

    worker.send('shutdown')
    worker.disconnect()

    promiseArray.push(new Promise((resolve) => {
      let resolved = false

      worker.once('exit', () => (!resolved && resolve(), resolved = true))
      setTimeout(() => (!resolved && resolve(), worker.kill('SIGTERM'), resolved = true), 4000)
    }))
  }

  Promise.all(promiseArray).then(callback)
}

<强> worker.js

function terminateWorker(server) {
  if (server && server.listening) {
    Store.store(STORE_KEYS.isTerminating, true)
    gracefulCloseSockets()
    server.close(endProcess)
  } else {
    endProcess()
  }
}

<强>解释

  1. 当主人收到“SIGTERM”时,他会调用close函数(上面的摘录)
  2. 工作人员收到“关闭”消息并调用terminateWorker函数(上面的摘录)。此函数关闭http.Server并等待所有套接字完成。