This commit is contained in:
zhouchangcheng 2024-05-27 14:27:46 +08:00
parent 4c36b37fa2
commit e35c59b4f8
3 changed files with 91 additions and 30 deletions

View File

@ -44,12 +44,13 @@ public function __construct()
public function handle(): int public function handle(): int
{ {
$chunk = $this->argument('chunk'); $chunk = $this->argument('chunk');
$this->line('开始消息队列'); $this->info('开始消息队列');
$res = apiRequest::api('/Notic/getNotics', []); $res = apiRequest::api('/Notic/getNotics', []);
if (!$res['result'] || $res['errCode'] != '0000') { if (!$res['result'] || $res['errCode'] != '0000') {
$this->error('request err: ' . $res['desc'] ?? ''); $this->error('request err: ' . $res['desc'] ?? '');
return 1; return 1;
} }
$count = 0;
$arr = $res['data']['notice_list'] ?? []; $arr = $res['data']['notice_list'] ?? [];
$typeIds = array_flip(range(1, 5)); $typeIds = array_flip(range(1, 5));
while ($items = array_splice($arr, 0, $chunk)) { while ($items = array_splice($arr, 0, $chunk)) {
@ -74,7 +75,6 @@ public function handle(): int
'notice_id' => $id, 'notice_id' => $id,
'notice_type' => $data[$id]['type'], 'notice_type' => $data[$id]['type'],
'raw_content' => json_encode($data[$id]), 'raw_content' => json_encode($data[$id]),
'err_message' => '',
'created_at' => $time, 'created_at' => $time,
]; ];
if (isset($typeIds[$data[$id]['type']])) { if (isset($typeIds[$data[$id]['type']])) {
@ -92,7 +92,9 @@ public function handle(): int
\App\Jobs\notice::dispatch($type, $item); \App\Jobs\notice::dispatch($type, $item);
Log::info('添加 type' . $type . '的队列', $item); Log::info('添加 type' . $type . '的队列', $item);
} }
$count += count($queue);
} }
$this->info('添加了' . $count . '条记录');
return 0; return 0;
} }
} }

View File

@ -23,6 +23,17 @@ class notice implements ShouldQueue
public Client $client; public Client $client;
/**
* 计算重试任务之前要等待的秒数
*
* @return array<int, int>
*/
public function backoff(): array
{
return [1, 5, 10];
}
/** /**
* Create a new job instance. * Create a new job instance.
*/ */
@ -33,6 +44,14 @@ public function __construct(public int $type, public mixed $data)
public string $goodsUrl; public string $goodsUrl;
/**
* 处理失败作业
*/
public function failed(Throwable $exception): void
{
// 向用户发送失败通知等...
}
/** /**
* Execute the job. * Execute the job.
* @throws GuzzleException * @throws GuzzleException
@ -40,13 +59,15 @@ public function __construct(public int $type, public mixed $data)
*/ */
public function handle(): void public function handle(): void
{ {
Log::info('开始执行type' . $this->type . ' 的队列'); Log::info('===========================开始执行type' . $this->type . ' 的队列============================');
try {
switch ($this->type) { switch ($this->type) {
case 1: case 1:
$this->addGoods(); $this->addGoods();
break; break;
case 2: case 2:
$this->updateGoods();
break;
case 3: case 3:
$this->changeProductState(); $this->changeProductState();
break; break;
@ -55,7 +76,12 @@ public function handle(): void
$this->changePrice(); $this->changePrice();
break; break;
} }
Log::info('执行完成'); Log::info('===========================执行完成================================');
} catch (Throwable $throwable) {
$this->fail($throwable);
Log::info('===========================执行出错================================');
throw $throwable;
}
} }
/** /**
@ -67,7 +93,6 @@ public function addGoods(): void
{ {
$goods = $goodsItems = $noticeIds = []; $goods = $goodsItems = $noticeIds = [];
$this->client = new Client(); $this->client = new Client();
$apiToken = env('API_TOKEN');
$now = date('Y-m-d H:i:s'); $now = date('Y-m-d H:i:s');
$good = new Good(); $good = new Good();
$goodsItem = new GoodsItem(); $goodsItem = new GoodsItem();
@ -86,7 +111,6 @@ public function addGoods(): void
continue; continue;
} }
$product = apiRequest::apis($this->goodsUrl, $this->client, [ $product = apiRequest::apis($this->goodsUrl, $this->client, [
'token' => $apiToken,
'itemId' => $item['result']['itemId'], 'itemId' => $item['result']['itemId'],
]); ]);
if ($product['errCode'] != '0000') { if ($product['errCode'] != '0000') {
@ -115,13 +139,49 @@ public function addGoods(): void
} }
}); });
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
\App\Models\Notice::query()->whereIn('notice_id', $noticeIds)
->update(['err_message' => $throwable->getMessage()]);
Log::error('添加商品失败', [$throwable->getMessage(), $throwable->getFile(), $throwable->getTrace()]); Log::error('添加商品失败', [$throwable->getMessage(), $throwable->getFile(), $throwable->getTrace()]);
throw $throwable; throw $throwable;
} }
} }
public function updateGoods(): void
{
$this->client = new Client();
$itemIds = $goods = $noticeIdMapItemId = [];
foreach ($this->data as $item) {
$noticeIdMapItemId[$item['result']['itemId']] = $item['notice_id'];
$product = apiRequest::apis($this->goodsUrl, $this->client, [
'itemId' => $item['result']['itemId'],
]);
if ($product['errCode'] != '0000') {
throw new Exception('request item ' . $item['item_id'] . ' err:' . $product['desc'] ?? '');
}
$product = $product['data']['product'];
$goods[$product['itemId']] = $product;
$itemIds[] = $product['itemId'];
}
DB::transaction(function () use ($goods, $itemIds, $noticeIdMapItemId) {
$items = Good::query()->whereIn('itemid', $itemIds)->with('good_item')->get();
$notices = [];
foreach ($items as $item) {
$item->fill($goods[$item->itemId]);
if ($item->isDirty()) {
$item->save();
}
$item->good_item->fill($goods[$item->itemId]);
if ($item->good_item->isDirty()) {
$item->good_item->save();
}
$notices[] = $noticeIdMapItemId[$item->itemId];
}
\App\Models\Notice::query()->whereIn('notice_id', $notices)
->update(['state', 3]);
});
}
/** /**
* @throws Throwable * @throws Throwable
*/ */
@ -132,17 +192,17 @@ public function changeProductState(): void
$idss[] = $item['notice_id']; $idss[] = $item['notice_id'];
$ids[$item['result']['state']][] = $item['result']['itemId']; $ids[$item['result']['state']][] = $item['result']['itemId'];
} }
$now = date('Y-m-d H:i:s');
try { try {
DB::transaction(function () use ($ids, $idss) { DB::transaction(function () use ($ids, $idss, $now) {
foreach ($ids as $state => $item) { foreach ($ids as $state => $item) {
Good::query()->whereIn('itemid', $item)->update(['state' => $state]); Good::query()->whereIn('itemid', $item)->update(['state' => $state, 'updated_at' => $now]);
} }
\App\Models\Notice::query()->whereIn('notice_id', $idss) \App\Models\Notice::query()->whereIn('notice_id', $idss)
->update(['state' => 3]); ->update(['state' => 3]);
}); });
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
\App\Models\Notice::query()->whereIn('notice_id', $idss) Log::error('修改状态失败', [$throwable->getMessage(), $throwable->getFile(), $throwable->getTrace()]);
->update(['err_message' => $throwable->getMessage()]);
throw $throwable; throw $throwable;
} }
} }
@ -155,9 +215,11 @@ public function changePrice(): void
$updateData = array_column($this->data, 'result'); $updateData = array_column($this->data, 'result');
$priceType = [4 => 'sell_price', 5 => 'settle_price']; $priceType = [4 => 'sell_price', 5 => 'settle_price'];
$tablePriceType = [4 => 'market_price', 5 => 'settlement']; $tablePriceType = [4 => 'market_price', 5 => 'settlement'];
$updateData = array_map(function ($item) use ($priceType, $tablePriceType) { $now = date('Y-m-d H:i:s');
$updateData = array_map(function ($item) use ($priceType, $tablePriceType, $now) {
$item[$tablePriceType[$this->type]] = $item[$priceType[$this->type]]; $item[$tablePriceType[$this->type]] = $item[$priceType[$this->type]];
unset($item[$priceType[$this->type]]); unset($item[$priceType[$this->type]]);
$item['updated_at'] = $now;
return $item; return $item;
}, $updateData); }, $updateData);
$ids = array_column($this->data, 'notice_id'); $ids = array_column($this->data, 'notice_id');
@ -168,11 +230,9 @@ public function changePrice(): void
->update(['state' => 3]); ->update(['state' => 3]);
}); });
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
\App\Models\Notice::query()->whereIn('notice_id', $updateData) Log::error('修改价格失败', [$throwable->getMessage(), $throwable->getFile(), $throwable->getTrace()]);
->update(['err_message' => $throwable->getMessage()]);
throw $throwable; throw $throwable;
} }
} }
} }

View File

@ -18,7 +18,6 @@ public function up()
$table->integer('notice_id')->unique()->comment('通知id'); $table->integer('notice_id')->unique()->comment('通知id');
$table->integer('notice_type')->comment('通知type'); $table->integer('notice_type')->comment('通知type');
$table->text('raw_content')->comment('原始消息内容'); $table->text('raw_content')->comment('原始消息内容');
$table->text('err_message')->comment('处理时错误信息');
$table->tinyInteger('state')->default(1)->comment('消息状态1待消费2消费进行中,3处理完成'); $table->tinyInteger('state')->default(1)->comment('消息状态1待消费2消费进行中,3处理完成');
$table->timestamps(); $table->timestamps();
}); });