群集

时间:2016-10-18 07:46:28

标签: node.js mongodb express mongoose node-cluster

我遇到了node.js / cluster和mongoose连接的问题。 我不确定我是否可以使用mongoose在同一个数据库上连接我的Web服务器的多个分支,是吗?

我的代码片段是:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const helmet = require('helmet');
const mongoose = require('mongoose');
const http = require('http');

if (cluster.isMaster) {
  const cpuCount = require('os').cpus();
  cpuCount.forEach((cpu) => {
    cluster.fork(); // fork web server
  });
  cluster.on('exit', (worker, code, signal) => {
    ... // log
    cluster.fork(); // on dying worker, respawn
  });
} else {

  //express middleware
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(helmet());
  ... // express and global config

  // The mongoose connection dit not work with cluster
  mongoose.connect(__DB_URL__); // where __DB_URL__ = 'mongodb://database/test'

  ... //server config
  const server = http.createServer(app);
  server.listen
}

我可以在不使用cluster(没有代码的第一部分)(或者使用cluster但没有使用mongoose ...)的情况下运行此服务器,当我使用cluster运行此服务器时;工人没有崩溃,但猫鼬连接!!

这是json错误:

{ MongoError: failed to connect to server [database:27017] on first connect
    at Pool.<anonymous> (/Users/...)
    ... // long path error
  name: 'MongoError',
  message: 'failed to connect to server [database:27017] on first connect' }

我真的能够在群集的每个分支中使用mongoose,还是有另一个解决方案?

1 个答案:

答案 0 :(得分:2)

试试这个为我工作....

 const express = require('express');
const app = express();
const bodyParser = require('body-parser');
//const helmet = require('helmet');
const mongoose = require('mongoose');
const cluster = require('cluster');
const http = require('http');

 var dbURI = 'mongodb://localhost:27017/dal'; 


// Create the database connection 
mongoose.connect(dbURI); 


mongoose.connection.on('connected', function () {  
 console.log('Mongoose default connection open to ' + dbURI);
 }); 


  mongoose.connection.on('error',function (err) {  
  console.log('Mongoose default connection error: ' + err);
 }); 


  mongoose.connection.on('disconnected', function () {  
  console.log('Mongoose default connection disconnected'); 
  });

 // If the Node process ends, close the Mongoose connection 
process.on('SIGINT', function() {  
 mongoose.connection.close(function () { 
console.log('Mongoose default connection disconnected through app      termination'); 
  process.exit(0); 
}); 
}); 


  if (cluster.isMaster) {
  const cpuCount = require('os').cpus();
  cpuCount.forEach((cpu) => {
   cluster.fork(); // fork web server
  });
  cluster.on('exit', (worker, code, signal) => {

    cluster.fork(); // on dying worker, respawn
  });
  } else {

    //express middleware
   app.use(bodyParser.json());
   app.use(bodyParser.urlencoded({ extended: false }));
   // app.use(helmet());

   app.listen(3000, function(){
console.log(3000);
  })
}