mongodb: Remote server has closed the connection


运行mongodb连接的时候,遇到了  Remote server has closed the connection 的错误问题。

这是预期的行为。

Connections to MongoDB are persistent. That means that we only create the connection the first time you do "new MongoClient(...)", any subsequent calls to "new MongoClient(..)" (in the same process) don't actually create a new connection.
These will look in our registry and see "hey, I already have connection to that server - I don't need to create another connection!"

Internally we do sanity checking on that connection every few seconds, both to check the latency of the server (by issuing ping commands), and to check its status (for example, is the server still the primary in a replicaset?). Both of these intervals are configurable (mongo.ping_interval and mongo.is_master_interval php.ini options).

Now, if the connection gets closed by the server at any point after we created the connection we won't be able to discover that until we attempt to use the connection for something.
This "something" can either be an action from the application (such as ->find(), ->insert(), ....), or one of those internal connection checking the driver does.
When we discover the broken connection we will clean it up from our persistent registry and then throw an exception.

It is your responsibility to handle the exception and decide what to do. In most cases, simply retrying the same action again will be the right choice, but we cannot take that for granted as that is considered to be business logic.

Now, in the example above:

php > $m = new MongoClient();
php > var_dump($m);
/* restart the mongod */
php > $m = new MongoClient();

The better way is:

<?php
function getMongoClient($seeds = "", $options = array(), $retry = 3) {
    try {
        return new MongoClient($seeds, $options);
    } catch(Exception $e) {
        /* Log the exception so we can look into why mongod failed later */
        logException($e);
    }
    if ($retry > 0) {
        return getMongoClient($seeds, $options, --$retry);
    }
    throw new Exception("I've tried several times getting MongoClient.. Is mongod really running?");
}
 
try {
    $mc = getMongoClient("localhost", array());
} catch(Exception $e) {
    /* Can't connect to MongoDB! */
    logException($e);
    die("Can't do anything :(");
}

完成。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM