123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- <?php
- declare(strict_types=1);
- namespace App\Master\Framework\Extend;
- use App\Utils\LogUtil;
- use Hyperf\AsyncQueue\Job;
- use Hyperf\Coroutine\Coroutine;
- class BaseJob extends Job
- {
- //日志板块
- protected string $LOG_MODULE = 'BaseJob';
- public $params;
- protected string $message = 'error';
- protected mixed $data = [];
- /**
- * 任务执行失败后的重试次数,即最大执行次数为 $maxAttempts+1 次
- */
- protected int $maxAttempts = 2;
- public function __construct($params)
- {
- // 这里最好是普通数据,不要使用携带 IO 的对象,比如 PDO 对象
- $this->params = $params;
- }
- /**
- * Execute the job.
- *
- * @return void
- */
- public function handle()
- {
- //日志统一写入
- LogUtil::getInstance('Queues/');//设置日志存入通道
- Coroutine::defer(function () {
- LogUtil::close();//协程结束后统一写入
- });
- LogUtil::info('开始处理', $this->LOG_MODULE, 'do', ['params' => $this->params]);
- // 根据参数处理具体逻辑
- // 通过具体参数获取模型等
- // 这里的逻辑会在 ConsumerProcess 进程中执行
- try {
- $res = $this->do($this->params);
- LogUtil::info('处理结果', $this->LOG_MODULE, 'do', [
- 'code' => $res,
- 'message' => $this->getMessage(),
- 'data' => $this->getData(),
- ]);
- } catch (\Exception $e){
- LogUtil::error('执行失败',$this->LOG_MODULE,__FUNCTION__,$e);
- }
- }
- /**
- * @param $params
- * @return true
- */
- protected function do($params)
- {
- // 业务代码
- return $this->success('执行成功', $params);
- }
- /**
- * 返回成功结果
- * @param string $message
- * @param mixed $data
- * @return bool
- */
- protected function success(string $message = 'success', mixed $data = []): bool
- {
- $this->message = $message;
- $this->data = $data;
- return true;
- }
- /**
- * 返回失败结果
- * @param string $message
- * @param mixed $data
- * @return bool
- */
- protected function error(string $message = 'error', mixed $data = []): bool
- {
- $this->message = $message;
- $this->data = $data;
- return false;
- }
- /**
- * 获取成功数据
- * @return mixed
- */
- public function getData(): mixed
- {
- return $this->data;
- }
- /**
- * 获取消息
- * @return string
- */
- public function getMessage(): string
- {
- return $this->message;
- }
- }
|