重新启动mongod服务后,当我尝试连接PHP时,我得到每个数据库的连接错误:
Failed to connect to: localhost:27017: Remote server has closed the connection
500 Internal Server Error - MongoConnectionException
一次或两次刷新后,连接再次工作。它不介意连接是在重启后立即建立还是在一段时间后建立。
MongoDB version: 2.6.4
PHP MongoDB driver version: 1.5.5
Configuration: PHP-FPM with Apache2
我认为使用了旧mongo实例的持久连接,但我找不到解决这个问题的方法。当第一个连接失败时,是否有任何方法可以强制Mongo驱动程序启动一个新的连接?
我们现在使用的解决方案是,我们重启MongoDB后重启Apache。这不是最好的解决方案,但它有效:)。
有同样的问题。我可以确认它与驱动程序中的连接池有关,我没有找到任何有价值的选项。我还可以确认,在数据库重启几个小时后,第一个新的MongoClient()调用会发生这种情况。
我所做的是用try catch包围我的新MongoClient()并重复它。例如:
try {
$NoSQLDBMS_Connection = new MongoClient( $NoSQLDBMS_Host );
$NoSQLDBMS_Database = $NoSQLDBMS_Connection->selectDB( $NoSQLDBMS_DBName );
} catch( Exception $e ) {
// retry, mostly when mongodb has been restarted in order to get a new connection
$MaxRetries = 5;
for( $Counts = 1; $Counts <= $MaxRetries; $Counts ++ ) {
try {
$NoSQLDBMS_Connection = new MongoClient( $NoSQLDBMS_Host );
$NoSQLDBMS_Database = $NoSQLDBMS_Connection->selectDB( $NoSQLDBMS_DBName );
} catch( Exception $e ) {
continue;
}
return;
}
// do something fancy here if mongodb is not reachable at all
}
重试。5倍只是偏执狂。我从来没有经历过需要多次重试。
希望能有所帮助。