因此能否在配置文件里设定超时时间,然后在时间到期前主动重连呢,经过实验是可以实现的,修改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];
}
只需要在配置文件databa以上是对断线重连的一点改进,如有不足之处,还望指点
注:仅支持DB操作,不支持模型操作
最佳答案
