【Laravel】MySQL server has gone away的解决版本
当用定时任务跑Laravel代码时,连接会超时,原因是在第一次model创建连接时会缓存起来,但连接经过一段时候后会超时断开,继续使用的时候就会出现
MySQL server has gone away
解决办法是在创建连接后记录一下连接创建时间,超过10s后自动重连保证model查询时连接是有效的
<?php use Illuminate\Database\Capsule\Manager; /** * Lavarel Model数据库连接初始化类 */ class CapsuleManagerInitializer { /** @var Manager */ private static $capsule = null; private static $connectionStartTime = null; public static function init() { self::initDBCapsule(); } /** * 初始化Illuminate Database Capsule * https://github.com/illuminate/database */ private static function initDBCapsule() { $time = time(); if (!self::$capsule) { $capsule = new Manager(); // 创建链接 $capsule->addConnection(self::getDBConfig('dbName'), 'connectionName'); $capsule->setFetchMode(\PDO::FETCH_ASSOC); self::$connectionStartTime = $time; // 设置全局静态可访问 $capsule->setAsGlobal(); // 启动Eloquent $capsule->bootEloquent(); self::$capsule = $capsule; } elseif ($time - self::$connectionStartTime > 10) { // 启动10秒后重连确保连接有效,避免MySQL server has gone away self::$capsule->getDatabaseManager()->connection('connectionName')->reconnect(); self::$connectionStartTime = $time; } } /** * 数据库配置 * * @return array */ private static function getDBConfig($dbConfig) { $config = [....]; return [ 'read' => [ 'host' => $config['slave']['host'], 'username' => $config['slave']['user'], 'password' => $config['slave']['password'], 'database' => $config['slave']['database'], ], 'write' => [ 'host' => $config['master']['host'], 'username' => $config['master']['user'], 'password' => $config['master']['password'], 'database' => $config['master']['database'], ], 'driver' => 'mysql', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ]; } }
Model的继承类
<?php use Illuminate\Database\Eloquent\Model; use Illuminate\Events\Dispatcher; class BaseModel extends Model { /** * 构造器并初始化数据库连接 * * @param array $attributes */ public function __construct(array $attributes = []) { $this->initConnection(); parent::__construct($attributes); } /** * 初始化数据库连接 */ protected function initConnection() { CapsuleManagerInitializer::init(); } }
标签: PHP
还没有人抢沙发呢~