解决"MySQL服务器已经消失"的错误

Raf*_*fay 16 php mysql connection phpmyadmin

我在PHP中编写了一些代码来返回.edu域中的html内容.这里给出简要介绍:PHP中Web爬虫的错误

当爬网链接的数量很少(大约40个URL)时爬虫工作正常,但是在这个数字之后我得到"MySQL服务器已经消失"错误.

我将html内容存储为MySQL表中的longtext,我不知道为什么错误在至少40-50次插入后到达.

在这方面的任何帮助都非常感谢.

请注意,我已经更改了wait_timeout和max_allowed_pa​​cket以容纳我的查询和php代码,现在我不知道该怎么做.请帮助我这方面.

rdl*_*rey 14

您可能倾向于通过在查询之前"ping"mysql服务器来处理此问题.这是一个坏主意.有关原因的更多信息,请查看此SO帖子:我应该在每次查询之前ping mysql服务器吗?

处理问题的最佳方法是在try/catch块内包装查询并捕获任何数据库异常,以便您可以适当地处理它们.这在长时间运行和/或守护程序类型的脚本中尤为重要.所以,这是一个非常基本的例子,使用"连接管理器"来控制对数据库连接的访问​​:

class DbPool {

    private $connections = array();

    function addConnection($id, $dsn) {
        $this->connections[$id] = array(
            'dsn' => $dsn,
            'conn' => null
        );
    }

    function getConnection($id) {
        if (!isset($this->connections[$id])) {
            throw new Exception('Invalid DB connection requested');
        } elseif (isset($this->connections[$id]['conn'])) {
            return $this->connections[$id]['conn'];
        } else {
            try {
                // for mysql you need to supply user/pass as well
                $conn = new PDO($dsn);

                // Tell PDO to throw an exception on error
                // (like "MySQL server has gone away")
                $conn->setAttribute(
                    PDO::ATTR_ERRMODE,
                    PDO::ERRMODE_EXCEPTION
                );
                $this->connections[$id]['conn'] = $conn;

                return $conn;
            } catch (PDOException $e) {
                return false;
            }
        }
    }

    function close($id) {
        if (!isset($this->connections[$id])) {
            throw new Exception('Invalid DB connection requested');
        }
        $this->connections[$id]['conn'] = null;
    }


}


class Crawler {

    private $dbPool;

    function __construct(DbPool $dbPool) {
        $this->dbPool = $dbPool;
    }

    function crawl() {
        // craw and store data in $crawledData variable
        $this->save($crawledData);
    }

    function saveData($crawledData) {
        if (!$conn = $this->dbPool->getConnection('write_conn') {
            // doh! couldn't retrieve DB connection ... handle it
        } else {
            try {
                // perform query on the $conn database connection
            } catch (Exception $e) {
                $msg = $e->getMessage();
                if (strstr($msg, 'MySQL server has gone away') {
                    $this->dbPool->close('write_conn');
                    $this->saveData($val);
                } else {
                    // some other error occurred
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不,这是一个你自己指定的异常类,并从`saveData()`函数内部抛出.我已经更新了`saveData`函数并在我的回答中添加了一个自定义的DbException类来反映这一点...... (2认同)