如何跨子进程共享mongoose连接?

时间:2013-09-10 21:05:28

标签: node.js mongoose connection-pooling child-process

我有以下db.js模块,负责管理mongoose:

'use strict';

module.exports = function(config) {
    var mongoose = require('mongoose');

    //mongoose.connect(config.connectionString);
    var db = mongoose.connection;
    db.open(config.server, config.database, config.port, {user: config.user, pass: config.password});
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', console.log.bind(console, 'connected to database server ' + config.server));
};

在我的app.js中,我只是致电var db = require('./db')(config.db);,我的应用程序中的所有模型都运行良好。

对于某些后台工作,我要求一堆子进程(使用worker-farm),因为我不知道如何传递连接对象(或者它是否均匀允许),我在每个中打开一个连接(调用db.js)。

问题是,过了一段时间我开始遇到每个子进程的错误:{ [Error: Trying to open unclosed connection.] state: 1 }。此外,由于这会在这些子进程中导致意外的Execption,因此worker-farm会重新启动它们 - 而且它们都陷入了无限的恐怖循环(是的,我可以解决循环 - 但我宁愿解决问题: ))。

我做错了什么?什么是在一群工人之间分享猫鼬连接的最佳方式?

0 个答案:

没有答案