84 lines
1.9 KiB
PHP
84 lines
1.9 KiB
PHP
<?php
|
|
/**
|
|
* Author: ykxiao
|
|
* Date: 2025/6/3
|
|
* Time: 下午10:55
|
|
* Description:
|
|
*
|
|
* (c) ykxiao <yk_9001@hotmail.com>
|
|
*
|
|
* This source file is subject to the MIT license that is bundled
|
|
* with this source code in the file LICENSE.
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Job;
|
|
|
|
use App\Context\ApiUrlContext;
|
|
use App\Context\QueueContext;
|
|
use App\Log\Log;
|
|
use Exception;
|
|
use Hyperf\AsyncQueue\Job;
|
|
use Hyperf\DbConnection\Db;
|
|
|
|
/**
|
|
* Author: ykxiao
|
|
* Date: 2025/6/3
|
|
* Time: 下午10:57
|
|
* Description: Job基础任务类.
|
|
*
|
|
* (c) ykxiao <yk_9001@hotmail.com>
|
|
*
|
|
* This source file is subject to the MIT license that is bundled
|
|
* with this source code in the file LICENSE.
|
|
*/
|
|
abstract class BaseJob extends Job
|
|
{
|
|
public function __construct(public array $data)
|
|
{
|
|
}
|
|
|
|
public function handle(): void
|
|
{
|
|
// 设置用户信息上下文信息
|
|
if (!empty($user = $this->data['user'])) {
|
|
QueueContext::setUser($user);
|
|
}
|
|
|
|
if (!empty($this->data['api_url'])) {
|
|
ApiUrlContext::setApiUrl($this->data['api_url']);
|
|
}
|
|
|
|
// 运行业务逻辑, 总是在事务中执行,保证事务的原子性
|
|
Db::beginTransaction();
|
|
try {
|
|
$this->process();
|
|
|
|
Db::commit();
|
|
} catch (Exception $e) {
|
|
Db::rollBack();
|
|
$this->logError($e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 子类必须实现的业务逻辑处理方法
|
|
*/
|
|
abstract protected function process(): void;
|
|
|
|
/**
|
|
* 日志记录,可按需扩展日志通道
|
|
*/
|
|
protected function logError(Exception $e): void
|
|
{
|
|
Log::get('queue', 'queue')->error(sprintf(
|
|
"[%s] %s in %s:%d\n%s",
|
|
static::class,
|
|
$e->getMessage(),
|
|
$e->getFile(),
|
|
$e->getLine(),
|
|
$e->getTraceAsString()
|
|
));
|
|
}
|
|
} |