【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();
    	}
    
    }


    本博客所有文章如无特别注明均为原创。
    复制或转载请以超链接形式注明转自枫芸志,原文地址《【Laravel】MySQL server has gone away的解决版本
    标签:
    分享:

还没有人抢沙发呢~

无觅相关文章插件,快速提升流量