129 lines
4.0 KiB
PHP
129 lines
4.0 KiB
PHP
<?php
|
|
|
|
namespace app\queue\redis;
|
|
|
|
use Webman\RedisQueue\Consumer;
|
|
use support\Log;
|
|
use app\common\model\WordpressSite;
|
|
use app\common\model\WordpressUsedCar;
|
|
use app\common\model\UsedCarDetail;
|
|
use app\common\service\WordpressSiteService;
|
|
|
|
class WordPressPush implements Consumer
|
|
{
|
|
// 要消费的队列名
|
|
public $queue = 'wordpress-push';
|
|
|
|
// 连接名
|
|
public $connection = 'default';
|
|
|
|
/**
|
|
* 消费 WordPress 推送任务
|
|
* @param array $data
|
|
* - car_id: 车辆ID
|
|
* - site_id: WordPress站点ID(可选,默认使用启用的站点)
|
|
*/
|
|
public function consume($data)
|
|
{
|
|
$carId = $data['car_id'] ?? null;
|
|
$siteId = $data['site_id'] ?? null;
|
|
|
|
if (empty($carId)) {
|
|
Log::error('WordPress推送:车辆ID为空', ['data' => $data]);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// 获取车辆信息
|
|
$car = UsedCarDetail::find($carId);
|
|
if (!$car) {
|
|
Log::warning('WordPress推送:车辆不存在', ['car_id' => $carId]);
|
|
return;
|
|
}
|
|
|
|
// 获取WordPress站点
|
|
if ($siteId) {
|
|
$site = WordpressSite::find($siteId);
|
|
} else {
|
|
$site = WordpressSite::where('status', 1)->first();
|
|
}
|
|
|
|
if (!$site) {
|
|
$msg = '没有启用的WordPress站点';
|
|
Log::warning('WordPress推送失败:' . $msg, ['car_id' => $carId]);
|
|
// 推送失败,更新车辆状态为5
|
|
$car->update(['status' => 5]);
|
|
return;
|
|
}
|
|
|
|
// 检查是否已推送过
|
|
$existing = WordpressUsedCar::where('wp_site_id', $site->id)
|
|
->where('used_car_id', $carId)
|
|
->where('status', 1)
|
|
->first();
|
|
|
|
if ($existing) {
|
|
Log::info('WordPress推送:车辆已推送过,跳过', [
|
|
'car_id' => $carId,
|
|
'wp_product_id' => $existing->wp_product_id
|
|
]);
|
|
return;
|
|
}
|
|
|
|
// 执行推送
|
|
$wpService = new WordpressSiteService();
|
|
$result = $wpService->createProductForNewSite($site, $carId);
|
|
|
|
// 推送成功(没有抛出异常),更新车辆状态为4
|
|
$car->update(['status' => 4]);
|
|
Log::info('WordPress推送成功,车辆状态已更新为推送成功', [
|
|
'car_id' => $carId,
|
|
'wp_post_id' => $result['result']['id'] ?? null,
|
|
]);
|
|
|
|
} catch (\Throwable $e) {
|
|
Log::error('WordPress推送异常', [
|
|
'car_id' => $carId,
|
|
'error' => $e->getMessage(),
|
|
'trace' => $e->getTraceAsString(),
|
|
]);
|
|
// 推送失败,更新车辆状态为5
|
|
try {
|
|
if ($car) {
|
|
$car->update(['status' => 5]);
|
|
}
|
|
} catch (\Throwable $updateError) {
|
|
Log::error('更新车辆状态失败', [
|
|
'car_id' => $carId,
|
|
'error' => $updateError->getMessage(),
|
|
]);
|
|
}
|
|
// 不再重新抛出异常,让队列正常处理下一条
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 消费失败回调
|
|
*/
|
|
public function onConsumeFailure(\Throwable $e, $package)
|
|
{
|
|
Log::error('WordPress推送消费失败', [
|
|
'error' => $e->getMessage(),
|
|
'package' => $package,
|
|
]);
|
|
|
|
// 获取车辆ID并更新状态
|
|
$carId = $package['data']['car_id'] ?? null;
|
|
if ($carId) {
|
|
try {
|
|
UsedCarDetail::where('id', $carId)->update(['status' => 5]);
|
|
} catch (\Throwable $updateError) {
|
|
Log::error('推送失败后更新车辆状态异常', [
|
|
'car_id' => $carId,
|
|
'error' => $updateError->getMessage(),
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|