goodsnotices/app/Console/Commands/HandleNotice.php

85 lines
2.2 KiB
PHP
Raw Normal View History

2024-05-24 07:55:55 +00:00
<?php
namespace App\Console\Commands;
2024-05-24 11:04:29 +00:00
use App\Models\Notice;
use GuzzleHttp\Client;
2024-05-24 07:55:55 +00:00
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Isolatable;
class HandleNotice extends Command implements Isolatable
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'handle:notice';
/**
* The console command description.
*
* @var string
*/
protected $description = '处理消息';
/**
* Create a new command instance.
*
* @return void
*/
2024-05-24 11:04:29 +00:00
public function __construct(public Client $client)
2024-05-24 07:55:55 +00:00
{
2024-05-24 11:04:29 +00:00
parent::__construct();;
2024-05-24 07:55:55 +00:00
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->line('开始消息队列');
2024-05-24 11:04:29 +00:00
$url = env('NOTICE_URL');
$res = json_decode($this->client->post($url)->getBody()->getContents(), true);
if (!$res['result'] || $res['errCode'] != '0000') {
$this->error('request err: ' . $res['desc'] ?? '');
return 1;
}
$arr = $res['data']['notice_list'] ?? [];
while ($items = array_splice($arr, 0, 1)) {
$ids = array_column($items, 'notice_id');
$data = array_column($items, null, 'notice_id');
if (!$ids) {
continue;
}
$hadIds = Notice::query()->select('id')->whereIn('id', $ids)->get()->toArray();
$hadIds = array_column($hadIds, 'id');
$newIds = array_diff($ids, $hadIds);
$notices = [];
$time = date('Y-m-d H:i:s');
foreach ($newIds as $id) {
$notices[] = [
'notice_id' => $id,
'raw_content' => json_encode($data[$id]),
'created_at' => $time,
];
}
try{
Notice::insert($notices);
}catch (\Exception $exception){
$this->error('insert err:'. $exception->getMessage());
}
//todo 入队
foreach ($newIds as $id){
\App\Jobs\notice::dispatch($data[$id]);
}
}
2024-05-24 07:55:55 +00:00
return 0;
}
}