集群 express.js 应用程序中的 Mongoose 重复连接

Mongoose duplicate connections in a clustered express.js app

我在我的 express.js 应用程序中添加了集群,并且我在应用程序中指定了 2 个工作人员,我通过 mongoose 连接到我的数据库,但是当我 运行 该应用程序时,我的猫鼬连接 (mongoose.connect) 运行s 两次。我试过把它放在主集群中,但它在子集群中不起作用,有什么办法可以确保数据库只连接一次?我为此使用了 Throng 模块,粗略的代码如下:

// Using this module for clustering
throng( { workers: 2, lifetime: Infinity, }, start);


// My express app code goes inside this function
function start() { 
  // Connecting via mongoose
  mongoose.connect('')

  // ....some other code here

 server.listen(port, () => { 
    var host = process.env.NODE_ENV == 'development' && 'localhost'; var port = process.env.NODE_ENV == 'development' && process.env.PORT;
    console.log(chalk.cyan(` app listening at http://${host}:${port}`));
 })
}

我不知道该怎么做,非常感谢任何帮助,谢谢!

每个:https://github.com/hunterloftis/throng#a-complex-example 我从来没有和人群一起工作过,但根据文档,这应该很接近。

throng({master, worker, count: 4})

// This will only be called once
function master() {
  console.log('Started master')

  // Connecting via mongoose
  mongoose.connect('')

  // ....some other code here

  server.listen(port, () => {
    var host = process.env.NODE_ENV == 'development' && 'localhost';
    var port = process.env.NODE_ENV == 'development' && process.env.PORT;
    console.log(chalk.cyan(` app listening at http://${host}:${port}`));
  })
  process.on('beforeExit', () => {
    console.log('Master cleanup.')
  })
}

// This will be called four times
function worker(id, disconnect) {
  let exited = false

  console.log(`Started worker ${id}`)
  process.on('SIGTERM', shutdown)
  process.on('SIGINT', shutdown)

  async function shutdown() {
    if (exited) return
    exited = true

    disconnect()
  }
}