Example Analysis of queue shmilyzxt/yii2-queue in Yii2
Editor to share with you the Yii2 queue shmilyzxt/yii2-queue example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
Shmilyzxt/yii2-queue simply explains:
1. I use the advanced version of yii2, let's start with the configuration code, here I use the mysql queue, first configuration file, I write the queue configuration items in the root directory common\ config\ main-local.php under the components array, change the database configuration. Copy composer copy after installation
Vendor\ shmilyzxt\ yii2-queue\ jobs\ jobs.sqlvendor\ shmilyzxt\ yii2-queue\ failed\ failed.sql
2 sql files to the database to establish the queue data table and the data table when the task fails.
two。 The start syntax of the push task:\ Yii::$app- > queue- > pushOn (new SendMial (), ['email'= >' 49783121roomqq.compositional head title title = > 'test','content'= >' email test'], 'email'). Let's go to vendor\ shmilyzxt\ queue\ queues\ DatabaseQueue.php to see the code, and the pushOn () method is written in the parent class vendor\ shmilyzxt\ queue\ base\ Queue.php of the DatabaseQueue class:
/ / queued public function pushOn ($job, $data ='', $queue = null) {/ / canPush checks whether the queue has reached the maximum task if ($this- > canPush ()) {/ / beforePush pre-queued event $this- > trigger (self::EVENT_BEFORE_PUSH); / / queued event $ret = $this- > push ($job, $data, $queue); / / afterPush queued event $this- > trigger (self::EVENT_AFTER_PUSH); return $ret } else {throw new\ Exception ("max jobs number exceed! The max jobs number is {$this- > maxJob} ");}}
Note: it's best to take a look at the yii2 event event class, http://www.digpage.com/event.html
About queuing: $this- > push ($job, $data, $queue); here in cooperation with the queue class file view, related functions jump, deal with the data recorded to the database. (function direction: getQueue ()-- > createPayload ()-- > pushToDatabase ()), pushOn () finally returns the result of inserting data into the database. The success $ret is 1.
3. Run the command in the background to process the queue, for example: php. / yii worker/listen default 10128 30, where default is the name of the queue, and an email queue is pushed above should be changed to email.
After starting the command, let's take a look at the code: first, execute the WorkerController controller actionListen method. We follow the code into the vendor\ shmilyzxt\ queue\ Worker.php-- listen method, which is actually looping all the time to execute the task of the operation queue:
/ * * enable a queue background listening task * @ param Queue $queue * @ param string $queueName listening queue name (the queue to which the task is pushed during pushon requires listening to the corresponding queue to get the task) * @ param int $attempt queue task failed attempts 0 is no limit to the maximum memory allowed by * @ param int $memory * @ param int $sleep interval for each detection * / public static function listen (Queue $queue, $queueName = 'default', $attempt = 10, $memory = 512, $sleep = 3, $delay = 0) {while (true) {try {/ / DatabaseQueue fetches an available task (instance) from the database queue, and update task $job = $queue- > pop ($queueName) } catch (\ Exception $e) {throw $e; continue;} if ($job instanceof Job) {/ / determine whether the number of execution errors is greater than the passed number of execution if ($attempt > 0 & & $job- > getAttempts () > $attempt) {$job- > failed ();} else {try {/ / throw new\ Exception ("test failed"); $job- > execute () } catch (\ Exception $e) {/ / failed to determine whether it has been deleted. Rejoin the queue if (! $job- > isDeleted ()) {$job- > release ($delay);}} else {self::sleep ($sleep);} if (self::memoryExceeded ($memory)) {self::stop ();}
Note: in $queue- > pop ($queueName); it is within the vendor\ shmilyzxt\ queue\ queues\ DatabaseQueue.php method to execute SQL using transactions and create an instance of vendor\ shmilyzxt\ queue\ jobs\ DatabaseJob.php
/ fetch a task public function pop ($queue = null) {$queue = $this- > getQueue ($queue); if (! is_null ($this- > expire)) {/ / $this- > releaseJobsThatHaveBeenReservedTooLong ($queue);} $tran = $this- > connector- > beginTransaction (); / / determine if there is an available task to execute if ($job = $this- > getNextAvailableJob ($queue) {$this- > markJobAsReserved ($job- > id); $tran- > commit () $config = array_merge ($this- > jobEvent, ['class' = >' shmilyzxt\ queue\ jobs\ DatabaseJob', 'queue' = > $queue,' job' = > $job, 'queueInstance' = > $this,]); return\ Yii::createObject ($config);} $tran- > commit (); return false;}
As for: $job- > execute (); is executed by DatabaseJob inheriting the parent class Job, and following the code is the event executed by yii\ base\ Component trigger
/ * execute task * / public function execute () {$this- > trigger (self::EVENT_BEFORE_EXECUTE, new JobEvent (["job" = > $this, 'payload' = > $this- > getPayload ()]); / / an event before beforeExecute executes a task does not have any executable code in JobEvent $this- > resolveAndFire () / / method of real task executed} / * method of real task execution (calling hander's handle method) * @ param array $payload * @ return void * / protected function resolveAndFire () {$payload = $this- > getPayload (); $payload = unserialize ($payload); / / deserialized data $type = $payload ['type']; $class = $payload [' job'] If ($type = = 'closure' & & ($closure = (new Serializer ()-> unserialize ($class [1])) instanceof\ Closure) {$this- > handler = $this- > getHander ($class [0]); $this- > handler- > closure = $closure; $this- > handler- > handle ($this, $payload [' data']);} else if ($type = 'classMethod') {$payload [' job'] [0]-> $payload ['job'] [1] ($this, $payload [' data']) } else if ($type = = 'staticMethod') {$payload [' job'] [0]: $payload ['job'] [1] ($this, $payload [' data']);} else {/ / executed `SendMail` class `handle ($job,$data) `method $this- > handler = $this- > getHander ($class); $this- > handler- > handle ($this, $payload ['data']);} / / Delete if (! $this- > isDeletedOrReleased ()) {$this- > delete ();}}
Finally, it comes to the handle ($job,$data) of the executed SendMail class, where the objects and data are pushed to the queue, and then our processing logic.
Public function handle ($job,$data) {if ($job- > getAttempts () > 3) {$this- > failed ($job);} $payload = $job- > getPayload (); echo''; print_r ($payload); / / $payload is the task data, you can email after you get the task data / / TODO email} these are all the contents of the article "sample Analysis of shmilyzxt/yii2-queue queue in Yii2". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!