我有一个连续循环运行的 Shell 脚本。
它检查数据库中的记录并在需要时更改它们。
set_time_limit(0);
while(true){
try{
$this->out(mysql_ping());
$companies = $this->findCompanies();
$companies = $this->reduceCompanies($companies, $rules);
$this->processCompanies($companies);
}catch (\Exception $e){
Log::write('debug', $e->getMessage());
$this->out($e->getMessage());
}
sleep(3);
}
我遇到的问题是这个脚本似乎运行正常,但随后会随机抛出: '2006 MySQL 服务器已经消失' 我试图在异常捕获中放入一些东西以重新连接到 mysql 服务器,例如:
}catch (\Exception $e){
if(!mysql_ping()){//tried
$this->connection->reconnect(); //also tried
$this->Company->getDatasource()->reconnect(); neither seem to work.
}}
关于如何重新连接到数据库有什么建议吗?
最佳答案
我有一个类似的问题,Shell 在无限循环中运行。
添加 ConnectionManager 的使用:
use Cake\Datasource\ConnectionManager;
在循环之前获取连接:
$connection = ConnectionManager::get('default');
在循环中,在您第一次需要连接之前不久,检查您是否仍处于连接状态,如果断开连接则进行连接:
if(!$connection->isConnected()) {
$connection->connect();
}
如果您的 Shell 处于等待较长时间的状态,您可以尝试手动断开连接并在再次需要连接时重新连接:
if($connection->isConnected()) {
$connection->disconnect();
}
关于mysql - cakephp 3.1 mysql 已经消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36899756/