Lae/app/Console/Commands/Init.php

71 lines
1.6 KiB
PHP
Raw Normal View History

2023-01-03 11:42:52 +00:00
<?php
namespace App\Console\Commands;
2023-01-04 12:18:22 +00:00
use App\Support\Cluster;
2023-01-03 11:42:52 +00:00
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
2023-01-04 12:18:22 +00:00
use Illuminate\Support\Facades\Redis;
2023-01-03 13:13:53 +00:00
use Illuminate\Support\Str;
2023-01-03 11:42:52 +00:00
use Symfony\Component\Console\Command\Command as CommandAlias;
class Init extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'init';
/**
* The console command description.
*
* @var string
*/
2023-01-04 18:17:33 +00:00
protected $description = '注册此节点到集群中。';
2023-01-03 11:42:52 +00:00
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
2023-01-04 18:17:33 +00:00
Artisan::call('optimize');
2023-01-04 12:18:22 +00:00
if (!config('settings.node.ip')) {
$this->error('请先配置节点 IP。');
return CommandAlias::FAILURE;
}
2023-01-03 13:13:53 +00:00
// 重写 .env 文件中的 NODE_ID
$this->info('正在重写 .env 文件中的 NODE_ID。');
$node_id = Str::random(8);
if (config('settings.node.type') === 'master') {
$node_id = 'master';
}
$env = file_get_contents(base_path('.env'));
$env = preg_replace('/^NODE_ID=.*$/m', 'NODE_ID=' . $node_id, $env);
file_put_contents(base_path('.env'), $env);
2023-01-03 11:42:52 +00:00
2023-01-03 13:13:53 +00:00
// 刷新配置缓存
$this->info('正在刷新配置缓存。');
Artisan::call('config:cache');
2023-01-03 11:42:52 +00:00
2023-01-03 13:13:53 +00:00
// redis 创建一个 hash
2023-01-04 12:18:22 +00:00
$this->info('正在注册节点。');
Cluster::registerThisNode();
$this->info('初始化完成。');
2023-01-03 11:42:52 +00:00
return CommandAlias::SUCCESS;
}
}