Composer在线学习地址:学习地址
夜深人静,你准备上线一个重要功能,它需要为你的
users
users
php artisan migrate
传统的Laravel数据库迁移,在执行
ALTER TABLE
难道就没有一种更优雅、更安全的方式来处理数据库结构变更吗?
答案是肯定的!幸好,PHP社区从来不缺乏优秀的解决方案,而今天我们要介绍的,正是如何利用Composer和
daursu/laravel-zero-downtime-migration
daursu/laravel-zero-downtime-migration
daursu/laravel-zero-downtime-migration
pt-online-schema-change
gh-ost
这意味着,当你的Laravel应用进行数据库迁移时,用户仍然可以正常访问和操作,不会感受到任何中断!
首先,通过Composer将这个包引入你的Laravel项目:
<pre class="brush:php;toolbar:false;">composer require daursu/laravel-zero-downtime-migration
前置条件: 这个包本身只是一个“桥梁”,它依赖于外部的Schema变更工具。你需要根据自己的选择,在服务器上安装对应的工具:
gh-ost
pt-online-schema-change
brew install percona-toolkit
sudo apt-get install percona-toolkit
在
config/database.php
driver
以
pt-online-schema-change
<pre class="brush:php;toolbar:false;">'connections' => [
// ... 其他连接
'zero-downtime' => [
'driver' => 'pt-online-schema-change', // 或 'gh-ost'
// 这是你的主数据库(写入权限)连接详情
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
// 传递给 pt-online-schema-change 或 gh-ost 的额外参数
'params' => [
'--nocheck-replication-filters',
'--nocheck-unique-key-change',
'--recursion-method=none', // 如果有复制集,需要配置此项
'--chunk-size=2000',
// 更多参数请参考 pt-online-schema-change 或 gh-ost 的官方文档
],
],
],注意:
params
pt-online-schema-change
gh-ost
现在,当你需要进行Schema变更时,不再使用Laravel默认的
Schema
ZeroDowntimeSchema
例如,为
users
phone_number
<pre class="brush:php;toolbar:false;"><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Daursu\ZeroDowntimeMigration\ZeroDowntimeSchema; // 引入 ZeroDowntimeSchema
class AddPhoneNumberToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
ZeroDowntimeSchema::table('users', function (Blueprint $table) {
$table->string('phone_number')->nullable()->after('email'); // 添加字段
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
ZeroDowntimeSchema::table('users', function (Blueprint $table) {
$table->dropColumn('phone_number'); // 回滚操作
});
}
}编写完迁移文件后,正常运行
php artisan migrate
daursu/laravel-zero-downtime-migration
pt-online-schema-change
gh-ost
pt-online-schema-change
Schema
ZeroDowntimeSchema
params
需要注意的“坑”:
gh-ost
pt-online-schema-change
ALTER TABLE
pt-online-schema-change
TestCase.php
setUp
ZeroDowntimeSchema::disable();
daursu/laravel-zero-downtime-migration
以上就是如何实现Laravel数据库零停机迁移?daursu/laravel-zero-downtime-migration助你轻松搞定!的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号