123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209 |
- <?php
- namespace crmeb\utils;
- use crmeb\traits\ErrorTrait;
- use think\exception\ValidateException;
- use think\facade\Config;
- use think\facade\Queue as QueueThink;
- use think\facade\Log;
- class Queue
- {
- use ErrorTrait;
-
- protected $do = 'doJob';
-
- protected $defaultDo;
-
- protected $job;
-
- protected $errorCount = 3;
-
- protected $data;
-
- protected $queueName = null;
-
- protected $secs = 0;
-
- protected $log;
-
- protected $rules = ['do', 'data', 'errorCount', 'job', 'secs', 'log'];
-
- protected static $instance;
-
- protected function __construct()
- {
- $this->defaultDo = $this->do;
- }
-
- public static function instance()
- {
- if (is_null(self::$instance)) {
- self::$instance = new static();
- }
- return self::$instance;
- }
-
- public function setQueueName(string $queueName)
- {
- $this->queueName = $queueName;
- return $this;
- }
-
- public function push(?array $data = null)
- {
- if (!$this->job) {
- return $this->setError('需要执行的队列类必须存在');
- }
- $jodValue = $this->getValues($data);
- $res = QueueThink::{$this->action()}(...$jodValue);
- if (!$res) {
- $res = QueueThink::{$this->action()}(...$jodValue);
- if (!$res) {
- Log::error('加入队列失败,参数:' . json_encode($jodValue));
- }
- }
- $this->clean();
- return $res;
- }
-
- public function clean()
- {
- $this->secs = 0;
- $this->data = [];
- $this->log = null;
- $this->queueName = null;
- $this->errorCount = 3;
- $this->do = $this->defaultDo;
- }
-
- protected function action()
- {
- return $this->secs ? 'later' : 'push';
- }
-
- protected function getValues($data)
- {
- $jobData['data'] = $data ?: $this->data;
- $jobData['do'] = $this->do;
- $jobData['errorCount'] = $this->errorCount;
- $jobData['log'] = $this->log;
- if (!class_exists($this->job)) {
- throw new ValidateException('需要执行的队列类不存在');
- }
- if ($this->do != $this->defaultDo) {
- $this->job .= '@' . Config::get('queue.prefix', 'eb_') . $this->do;
- }
- if ($this->secs) {
- return [$this->secs, $this->job, $jobData, $this->queueName];
- } else {
- return [$this->job, $jobData, $this->queueName];
- }
- }
-
- public function __call($name, $arguments)
- {
- if (in_array($name, $this->rules)) {
- if ($name === 'data') {
- $this->{$name} = $arguments;
- } else {
- $this->{$name} = $arguments[0] ?? null;
- }
- return $this;
- } else {
- throw new \RuntimeException('Method does not exist' . __CLASS__ . '->' . $name . '()');
- }
- }
- }
|