zoukankan      html  css  js  c++  java
  • ThinkPHP出现General error: 2006 MySQL server has gone away的解决方法

    错误:

    #13 {main}SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
    FILE: ThinkPHPLibraryThinkDbDriver.class.php(169)


    原因分析:

    本次错误提示是在cli模式运行,隔一段时间就会出现,查询资料后发现mysql默认没隔8个小时(2880000秒)就会断开


    解决方案,解决方式找了三个

    方法1

      配置mysql.cnf(windows系统则是my.ini),指定wait_timeout和interactive_timeout,设置一个比较大的值,比如一年(86400*365)。

    方法2

      链接后通过执行命令来指定本次链接的wait_timeout和interactive_timeout,原理跟【1】一样,只不过这种方式只影响本次链接,方式【1】会影响所有链接。

      但是thinkphp已经封装好了数据库驱动,所以不好单独指定某一次。我的做法是判断php_sapi,如果是cli则设置wait_timeout和interactive_timeout

    // ThinkPHPLibraryThinkDbDriver.class.php 第 105行
    if(PHP_SAPI == 'cli'){
         $query = $this->linkID[$linkNum]->prepare("set session wait_timeout=31536000,interactive_timeout=31536000,net_read_timeout=10000");
         $query->execute();
    }

    方法3

    既然是超时断开了,那我们就可以采取断线重连的方式

    
    
    // ThinkPHPLibraryThinkDbDriver.class.php 第 105行
    $this->linkID[$linkNum]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->linkID[$linkNum]->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
    $this->linkID[$linkNum]->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    // ThinkPHPLibraryThinkDbDriver.class.php 第159行(query方法) 和 220行(execute方法)
    try {
                $this->PDOStatement = $this->_linkID->prepare($str);
            } catch (PDOException $e) {
                // 断线重连
                if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
                    echo "---> db reconnecting...
    ";
                    $this->linkID = array();
                    $this -> _linkID = null;
                    $this->initConnect(false);
                    $this->PDOStatement = $this->_linkID->prepare($str);
                }
            }
  • 相关阅读:
    cropper图片剪裁 , .toBlob()报错
    clipboard异步复制文本(动态获取文本)
    ng-model 数据不更新 及 ng-repeat【ngRepeat:dupes】错误
    MongoVUE的Collections数据不显示的解决方法
    AngularJS监听路由变化
    bootstrap在ie8下,兼容媒体查询
    css3 animation动画特效插件的巧用
    前端图片canvas,file,blob,DataURL等格式转换
    「每日一码」(精品代码,质量保证)阶乘
    「每日一码」(精品代码,质量保证)empty和undefined
  • 原文地址:https://www.cnblogs.com/dragondean/p/8428597.html
Copyright © 2011-2022 走看看