Yii2 queue shmilyzxt/yii2-queue overview, yii2shmilyzxt

Source: Internet
Author: User

Yii2 queue shmilyzxt/yii2-queue overview, yii2shmilyzxt

Shmilyzxt/yii2-queue:

1. I used the yii2 advanced edition. We started to look at the code from the configuration. Here I used the mysql queue. First, I wrote the queue configuration item in the root directory.common\config\main-local.phpUnder componentsUnder the array, change the database configuration. CopycomposerCopy after installation

vendor\shmilyzxt\yii2-queue\jobs\jobs.sqlvendor\shmilyzxt\yii2-queue\failed\failed.sql

Two SQL files are used to create queue data tables and data tables when task execution fails.

2. Push task start Syntax :\Yii::$app->queue->pushOn(new SendMial(),['email'=>'49783121@qq.com','title'=>'test','content'=>'email test'],'email');We arrivedvendor\shmilyzxt\queue\queues\DatabaseQueue.phpLet's take a look at the code. The pushOn () method is written inDatabaseQueueClass Parent classvendor\shmilyzxt\queue\base\Queue.phpMedium:

// Public function pushOn ($ job, $ data = '', $ queue = null) {// canPush check whether the queue has reached the maximum task volume if ($ this-> canPush () {// beforePush events before the queue $ this-> trigger (self :: EVENT_BEFORE_PUSH); // $ ret = $ this-> push ($ job, $ data, $ queue ); // events after afterPush enters the queue $ 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 is best to look at yii2 event class, http://www.digpage.com/event.html

About the incoming queue:$this->push($job, $data, $queue);,Here, we can use the queue file to view the relevant function jump and process the data records to the database. (function direction:getQueue()-->createPayload()-->pushToDatabase()),pushOn()Finally, the result of data insertion into the database is returned. Success $ ret is 1.

3. run commands in the background to process the queue, for example:php ./yii worker/listen default 10 128 3 0 Here, default is the queue name, and an email queue pushed above should be changed to email.

After the command is started, let's look at the code: first execute:WorkerControllerControllerctionListenMethod, we followed the codevendor\shmilyzxt\queue\Worker.php -- listenMethod, here is actually a loop that executes the tasks in the Operation queue:

/*** Enable a Queue background Listening Task * @ param queue $ Queue * @ param string $ queueName name of the queue to which the task is pushed during pushon, you need to listen to the corresponding queue to get the task) * @ param int $ attempt the number of failed attempts of the queue task, 0 is not limited * @ param int $ maximum memory used by memory * @ param int $ interval of each sleep detection */public static function listen (Queue $ queue, $ queueName = 'default', $ attempt = 10, $ memory = 512, $ sleep = 3, $ delay = 0) {while (true) {try {// DatabaseQueue retrieves an available task (Instance) from the database queue and updates the 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 number of input executions if ($ attempt> 0 & $ job-> getAttempts ()> $ attempt) {$ job-> failed ();} else {try {// throw new \ Exception ("test failed"); $ job-> execute ();} catch (\ Exception $ e) {// execution failed, judge whether it is deleted, re-join if (! $ Job-> isDeleted () {$ job-> release ($ delay) ;}}} else {self: sleep ($ sleep);} if (self :: memoryExceeded ($ memory) {self: stop ();}}}

Note: In$queue->pop($queueName);Yesvendor\shmilyzxt\queue\queues\DatabaseQueue.phpUse transactions to execute SQL statements and createvendor\shmilyzxt\queue\jobs\DatabaseJob.phpInstance

// Retrieve a task public function pop ($ queue = null) {$ queue = $ this-> getQueue ($ queue); if (! Is_null ($ this-> expire) {// $ this-> releaseJobsThatHaveBeenReservedTooLong ($ queue);} $ tran = $ this-> connector-> beginTransaction (); // determine whether an available task needs to be executed 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:$job->execute(); It is executed by DatabaseJob inheriting the parent class Job and following the code to find ityii\base\Component triggerExecuted event,

/*** Run the task */public function execute () {$ this-> trigger (self: EVENT_BEFORE_EXECUTE, new JobEvent (["job" => $ this, 'payload' => $ this-> getPayload ()]); // The event before beforeExecute executes the task does not have any executable code in JobEvent $ this-> resolveAndFire (); // method of the truly executed task}/*** real task execution method (call the handle method of hander) * @ param array $ payload * @ return void */protected function resolveAndFire () {$ payload = $ this-> getPayload (); $ payload = unseria Lize ($ payload); // deserialize 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, $ pay Load ['data']);} else if ($ type = 'staticmethod') {$ payload ['job'] [0]: $ payload ['job'] [1] ($ this, $ payload ['data']);} else {// The 'handle ($ job, $ data) 'method of the 'sendmail' class to be executed $ this-> handler = $ this-> getHander ($ class ); $ this-> handler-> handle ($ this, $ payload ['data']);} // Delete if (! $ This-> isDeletedOrReleased () {$ this-> delete ();}}

Finally,SendMailClasshandle($job,$data)Here is the object and data pushed to the queue, followed by our processing logic.

Public function handle ($ job, $ data) {if ($ job-> getAttempts ()> 3) {$ this-> failed ($ job );} $ payload = $ job-> getPayload (); echo '<pre>'; print_r ($ payload); // $ payload is the task data, after you get the task data, you can send an email // TODO email}

Summary

The above is a small series to introduce you to Yii2 queue shmilyzxt/yii2-queue introduction, hope to help everyone, if you have any questions please leave a message, small series will reply to you in time. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.