关于TP5断线重连的一点改进

浏览:1633 发布日期:2017/07/26 分类:技术分享 关键字: 断线重连
大部分开发者都知道,断线重连机制是依靠捕获SQL的错误 has gone away 实现的,但是错误既然已经发生,此时再重连,对某些业务来说,可能是致命的
因此能否在配置文件里设定超时时间,然后在时间到期前主动重连呢,经过实验是可以实现的,修改Db::connect 代码可以解决这个问题  public static function connect($config = [], $name = false)
    {
        $time   = time();        
        if (false === $name) {
            $name = md5(serialize($config));
            //执行超时重连
            if(isset(self::$timeOut[$name])){                
               
                $time  -= self::$timeOut[$name]['time'];
                if($time > self::$timeOut[$name]['time_out']){
                    self::$instance[$name] = null;             
                    unset(self::$instance[$name]);                     
                }
            }
        }
        if (true === $name || !isset(self::$instance[$name])) {
            // 解析连接参数 支持数组和字符串
            $options = self::parseConfig($config);
            if (empty($options['type'])) {
                throw new \InvalidArgumentException('Undefined db type');
            }
            $class = false !== strpos($options['type'], '\\') ? $options['type'] : '\\think\\db\\connector\\' . ucwords($options['type']);
            // 记录初始化信息
            if (App::$debug) {
                Log::record('[ DB ] INIT ' . $options['type'], 'info');
            }
            if (true === $name) {
                return new $class($options);
            } else {
                self::$instance[$name] = new $class($options); 
                //存放当前的连接时间和超时时间            
                if(!empty($options['time_out'])){                    
                    self::$timeOut[$name] = [
                        'time'     => time(),
                        'time_out' => $options['time_out']  
                    ];                    
                }   
            }
        }
      return self::$instance[$name];
    }
只需要在配置文件database里 添加time_out 即可
以上是对断线重连的一点改进,如有不足之处,还望指点
注:仅支持DB操作,不支持模型操作
最佳答案
评论( 相关
后面还有条评论,点击查看>>