作者 刘锟

项目升级

<?php
namespace App\Console\Commands\Update;
use App\Models\Com\UpdateLog;
use App\Models\Product\Keyword;
use App\Models\RouteMap\RouteMap;
use App\Services\ProjectServer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* 4.0,5.0升级到6.0,内容同步
* Class ProjectImport
* @package App\Console\Commands
* @author Akun
* @date 2023/10/9 15:04
*/
class ProjectUpdate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'project_update';
/**
* The console command description.
*
* @var string
*/
protected $description = '执行项目升级任务';
public function handle()
{
while (true) {
$this->start_update();
}
}
protected function start_update()
{
$task_id = $this->get_task();
if (!$task_id) {
sleep(2);
return true;
}
$task = UpdateLog::where('id', $task_id)->where('status', UpdateLog::STATUS_UN)->first();
if (!$task) {
sleep(2);
return true;
}
$project_id = $task->project_id;
$api_type = $task->api_type;
$api_url_arr = explode('?', $task->api_url);
$api_url = $api_url_arr[0];
echo 'date:' . date('Y-m-d H:i:s') . ', task_id: ' . $task->id . ', task_type: ' . $api_type . ', update start' . PHP_EOL;
$task->status = UpdateLog::STATUS_ING;//同步中
$task->save();
//设置数据库
$project = ProjectServer::useProject($task->project_id);
if ($project) {
if ($api_type == 'website_info') {
$url = $api_url . '?' . http_build_query(['w' => 'website_info']);
$data = http_get($url, ['charset' => 'UTF-8']);
if (isset($data['code']) && $data['code'] == 200) {
$tags = $data['data']['tags'] ?? [];
$model = new Keyword();
foreach ($tags as $tag) {
$keyword = $model->read(['title' => $tag], 'id');
if (!$keyword) {
$id = $model->addReturnId([
'project_id' => $project_id,
'title' => $tag
]);
$route = RouteMap::setRoute($tag, RouteMap::SOURCE_PRODUCT_KEYWORD, $id, $project_id);
$model->edit(['url' => $route], ['id' => $id]);
}
}
}
}
}
//关闭数据库
DB::disconnect('custom_mysql');
$task->status = UpdateLog::STATUS_COM;//同步完成
$task->save();
echo 'date:' . date('Y-m-d H:i:s') . ', task_id: ' . $task->id . ', task_type: ' . $api_type . ', update end ' . PHP_EOL;
sleep(2);
}
//获取任务
protected function get_task()
{
$key = 'console_update_task';
$task_id = Redis::rpop($key);
if ($task_id) {
return $task_id;
}
$task_list = UpdateLog::where('status', UpdateLog::STATUS_UN)->limit(20)->get();
if ($task_list->count() == 0) {
return false;
}
foreach ($task_list as $value) {
Redis::lpush($key, $value->id);
}
$task_id = Redis::rpop($key);
return $task_id;
}
}
... ...
... ... @@ -9,9 +9,9 @@ class UpdateLog extends Model
//设置关联表名
protected $table = 'gl_update_log';
const STATUS_PENDING = 0;
const STATUS_SUCCESS = 1;
const STATUS_FAIL = 2;
const STATUS_UN = 0;//未开始
const STATUS_ING = 1;//导入中
const STATUS_COM = 2;//导入完成
/**
* 创建更新日志
... ...