处理MongoError的好方法:服务器实例池已损坏 [英] Good way of handling MongoError: server instance pool was destroyed

查看:757
本文介绍了处理MongoError的好方法:服务器实例池已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行带有mongo连接池的守护程序.它可以正常运行数天,但最终会崩溃,并且随后的每个请求都收到此错误:

I'm running a daemon with a mongo connection pool. It runs fine for days but eventually it crashes and every subsequent request gets this error:

MongoError:服务器实例池已损坏

MongoError: server instance pool was destroyed

代码与此类似:

var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();

MongoClient.connect(config.mongo.url, function(err, db) {

    app.use('/', function(req, res, next) {
        db.collection('somecollection').find({}).toArray(function(err, result) {
            console.log(result);
        });
    })

    var server = require('http').Server(app);
    server.listen(config.worker.port, function() {
        var address = server.address();
        logger.info({
            address: address.address,
            port: address.port
        }, 'New Worker created');
    });
});

重新启动过程可以解决此问题,但是我希望应用程序以某种方式优雅地重新连接并在那里重新设置"db"对象.

Restarting the process fixes the issue, but I would like the application to somehow elegantly reconnect and reset the "db" object there.

推荐答案

这是我们正在使用的-如果连接失败,它将在5秒钟后尝试重新连接.它是为猫鼬编写的,但我们仅在检测错误时才重新运行连接,这对于任何框架都应完成.

This is what we are using - if connection fails, it tries to reconnect after 5 seconds. It is written for mongoose, but we are just re-running connection when detecting error, which should be done for any framework.

// Connect to mongodb
    const connect = function () {
        const options = {server: {socketOptions: {keepAlive: 1}}};
        mongoose.connect(config.db, options);
    };
    connect();

    mongoose.connection.on('error', err => {
        let stack;
        if (err) {
            stack = err.stack;
        }
        winston.error('Mongo crashed with error', {err, stack});
    }); // eslint-disable-line no-console
    mongoose.connection.on('disconnected', () => {
        setTimeout(connect, 5000);
    });

这篇关于处理MongoError的好方法:服务器实例池已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆