goodsnotices/app/Console/Commands/HandleNotice.php
zhouchangcheng e35c59b4f8 完善
2024-05-27 14:27:46 +08:00

101 lines
2.8 KiB
PHP

<?php
namespace App\Console\Commands;
use App\helpers\apiRequest;
use App\Models\Notice;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Isolatable;
use Illuminate\Support\Facades\Log;
class HandleNotice extends Command implements Isolatable
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'handle:notice {chunk=1000 : 分片}';
/**
* The console command description.
*
* @var string
*/
protected $description = '处理消息';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();;
}
/**
* Execute the console command.
*
* @return int
* @throws GuzzleException
*/
public function handle(): int
{
$chunk = $this->argument('chunk');
$this->info('开始消息队列');
$res = apiRequest::api('/Notic/getNotics', []);
if (!$res['result'] || $res['errCode'] != '0000') {
$this->error('request err: ' . $res['desc'] ?? '');
return 1;
}
$count = 0;
$arr = $res['data']['notice_list'] ?? [];
$typeIds = array_flip(range(1, 5));
while ($items = array_splice($arr, 0, $chunk)) {
$ids = array_column($items, 'notice_id');
if (!$ids) {
continue;
}
$data = array_column($items, null, 'notice_id');
$hadIds = Notice::query()->select('notice_id')->whereIn('notice_id', $ids)->get()->toArray();
$hadIds = array_column($hadIds, 'notice_id');
$newIds = array_diff($ids, $hadIds);
if (!$newIds) {
continue;
}
$notices = [];
$time = date('Y-m-d H:i:s');
$queue = [];
foreach ($newIds as $id) {
$notices[] = [
'notice_id' => $id,
'notice_type' => $data[$id]['type'],
'raw_content' => json_encode($data[$id]),
'created_at' => $time,
];
if (isset($typeIds[$data[$id]['type']])) {
$queue[$data[$id]['type']][] = $data[$id];
}
}
try {
Notice::insert($notices);
} catch (\Exception $exception) {
$this->error('insert err:' . $exception->getMessage());
continue;
}
foreach ($queue as $type => $item) {
\App\Jobs\notice::dispatch($type, $item);
Log::info('添加 type' . $type . '的队列', $item);
}
$count += count($queue);
}
$this->info('添加了' . $count . '条记录');
return 0;
}
}