BaseJob.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Master\Framework\Extend;
  4. use App\Utils\LogUtil;
  5. use Hyperf\AsyncQueue\Job;
  6. use Hyperf\Coroutine\Coroutine;
  7. class BaseJob extends Job
  8. {
  9. //日志板块
  10. protected string $LOG_MODULE = 'BaseJob';
  11. public $params;
  12. protected string $message = 'error';
  13. protected mixed $data = [];
  14. /**
  15. * 任务执行失败后的重试次数,即最大执行次数为 $maxAttempts+1 次
  16. */
  17. protected int $maxAttempts = 2;
  18. public function __construct($params)
  19. {
  20. // 这里最好是普通数据,不要使用携带 IO 的对象,比如 PDO 对象
  21. $this->params = $params;
  22. }
  23. /**
  24. * Execute the job.
  25. *
  26. * @return void
  27. */
  28. public function handle()
  29. {
  30. //日志统一写入
  31. LogUtil::getInstance('Queues/');//设置日志存入通道
  32. Coroutine::defer(function () {
  33. LogUtil::close();//协程结束后统一写入
  34. });
  35. LogUtil::info('开始处理', $this->LOG_MODULE, 'do', ['params' => $this->params]);
  36. // 根据参数处理具体逻辑
  37. // 通过具体参数获取模型等
  38. // 这里的逻辑会在 ConsumerProcess 进程中执行
  39. try {
  40. $res = $this->do($this->params);
  41. LogUtil::info('处理结果', $this->LOG_MODULE, 'do', [
  42. 'code' => $res,
  43. 'message' => $this->getMessage(),
  44. 'data' => $this->getData(),
  45. ]);
  46. } catch (\Exception $e){
  47. LogUtil::error('执行失败',$this->LOG_MODULE,__FUNCTION__,$e);
  48. }
  49. }
  50. /**
  51. * @param $params
  52. * @return true
  53. */
  54. protected function do($params)
  55. {
  56. // 业务代码
  57. return $this->success('执行成功', $params);
  58. }
  59. /**
  60. * 返回成功结果
  61. * @param string $message
  62. * @param mixed $data
  63. * @return bool
  64. */
  65. protected function success(string $message = 'success', mixed $data = []): bool
  66. {
  67. $this->message = $message;
  68. $this->data = $data;
  69. return true;
  70. }
  71. /**
  72. * 返回失败结果
  73. * @param string $message
  74. * @param mixed $data
  75. * @return bool
  76. */
  77. protected function error(string $message = 'error', mixed $data = []): bool
  78. {
  79. $this->message = $message;
  80. $this->data = $data;
  81. return false;
  82. }
  83. /**
  84. * 获取成功数据
  85. * @return mixed
  86. */
  87. public function getData(): mixed
  88. {
  89. return $this->data;
  90. }
  91. /**
  92. * 获取消息
  93. * @return string
  94. */
  95. public function getMessage(): string
  96. {
  97. return $this->message;
  98. }
  99. }