1

我有一个循环连续运行的 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 server has gone away' 我试图在异常捕获中放入一些东西以重新连接到 mysql 服务器,例如:

     }catch (\Exception $e){
                    if(!mysql_ping()){//tried 
    $this->connection->reconnect();  //also tried
$this->Company->getDatasource()->reconnect();   neither seem to work.
                    }}

有什么建议如何重新连接到数据库?

4

1 回答 1

1

我有一个类似的问题,Shell 在无限循环中运行。

添加 ConnectionManager 的使用:

use Cake\Datasource\ConnectionManager;

在循环之前获取连接:

$connection = ConnectionManager::get('default');

在循环中,在您第一次需要连接之前不久,检查您是否仍然连接并在断开连接时进行连接:

if(!$connection->isConnected()) {
    $connection->connect();
}

如果您的 Shell 处于等待较长时间的状态,您可以尝试手动断开连接并在再次需要连接时进行新连接:

if($connection->isConnected()) {
    $connection->disconnect();
}
于 2016-07-15T16:10:32.117 回答