123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\Storage;
- use Symfony\Component\Process\Process;
- class BackupDb extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'tty:backupDb {--I|import= : 导入数据库}';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = '备份数据库';
- protected $process;
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct()
- {
- parent::__construct();
- }
- /**
- * Execute the console command.
- *
- * @return int
- */
- public function handle()
- {
- $import = $this->option('import');
- //设置超时时间为0,表示一直执行。当php在safe mode模式下无效,此时可能会导致导入超时,此时需要分段导入
- set_time_limit(0);
- if ($import) {
- $this->info('正在执行恢复操作');
- $this->importData($import);
- } else {
- $this->info('正在执行备份操作');
- $this->exportData();
- }
- return 0;
- }
- private function exportData()
- {
- $DB_HOST = getenv('DB_HOST');
- $DB_DATABASE = getenv('DB_DATABASE');
- $DB_USERNAME = getenv('DB_USERNAME');
- $DB_PASSWORD = getenv('DB_PASSWORD');
- if (!Storage::exists('db_backup')) {
- Storage::makeDirectory('db_backup');
- }
- $dumpFilename = storage_path('app/db_backup/' . date("Y-m-d_H-i-s") . ".sql");
- $command = "mysqldump --host=" . $DB_HOST . " --user=" . $DB_USERNAME . " --password=" . $DB_PASSWORD . " --databases " . $DB_DATABASE . " > " . $dumpFilename;
- $process = Process::fromShellCommandline($command, null, null, null, null);
- $process->start();
- $process->wait();
- $this->info('备份成功!');
- // 保留最近的30天数据
- $fileArr = Storage::allFiles('db_backup');
- sort($fileArr);
- $limit = 30;
- if (count($fileArr) > $limit) {
- for ($i = 0; $i < count($fileArr) - $limit; $i++) {
- Storage::delete($fileArr[$i]);
- $this->info('删除数据库备份文件:' . $fileArr[$i]);
- }
- }
- }
- /**
- * 导入数据
- */
- private function importData($file_name)
- {
- $file_name = storage_path('app/db_backup/' . $file_name); //要导入的SQL文件名
- $file_name = str_replace('\\', '/', $file_name);
- $DB_HOST = getenv('DB_HOST');
- $DB_DATABASE = getenv('DB_DATABASE');
- $DB_USERNAME = getenv('DB_USERNAME');
- $DB_PASSWORD = getenv('DB_PASSWORD');
- $command = "mysql --host=$DB_HOST --user=$DB_USERNAME " . "--password=" . $DB_PASSWORD . " " . $DB_DATABASE . " < " . $file_name;
- Process::fromShellCommandline($command)->run(function ($type, $buffer) {
- if (Process::ERR === $type) {
- $this->info('failed - 数据库恢复失败!');
- } else {
- $this->info('数据库恢复成功!');
- }
- });
- }
- }
|