运行mongodb连接的时候,遇到了 Remote server has closed the connection 的错误问题。而且是随机性发生的。
在Yii2中,需要进行的修改为:
Yii2-mongodb/Connecting.php
修改函数:
public function open() { if ($this->mongoClient === null) { if (empty($this->dsn)) { throw new InvalidConfigException($this->className() . '::dsn cannot be empty.'); } $token = 'Opening MongoDB connection: ' . $this->dsn; try { Yii::trace($token, __METHOD__); Yii::beginProfile($token, __METHOD__); $options = $this->options; $options['connect'] = true; if ($this->defaultDatabaseName !== null) { $options['db'] = $this->defaultDatabaseName; } // $this->mongoClient = new \MongoClient($this->dsn, $options); $this->mongoClient = $this->getCustomMongoClient($options); $this->initConnection(); Yii::endProfile($token, __METHOD__); } catch (\Exception $e) { Yii::endProfile($token, __METHOD__); throw new Exception($e->getMessage(), (int) $e->getCode(), $e); } } }
添加函数
public function getCustomMongoClient($options,$retry = 4) { try { return new \MongoClient($this->dsn, $options); } catch(Exception $e) { /* Log the exception so we can look into why mongod failed later */ //logException($e); } if ($retry > 0) { return $this->getCustomMongoClient($options, --$retry); } throw new Exception("I've tried several times getting MongoClient.. Is mongod really running?"); }
也就是通过多次尝试连接的方式。