Home Backend Development PHP Tutorial Introduction to PHPyii2 queue shmilyzxt/yii2-queue

Introduction to PHPyii2 queue shmilyzxt/yii2-queue

Aug 04, 2017 am 10:42 AM

  • I feel very good during the use. I suggest you take a look at the principles of queues.

  • ##shmilyzxt/yii2-queue Simple explanation:

  1. I use the yii2 advanced version. Let’s start with the configuration and look at the code. Here I use mysql queue. First configure the file. I put

    queueThe configuration items are written under the components array in the root directory common\config\main-local.php, change the database configuration. Copy composerCopy after installation
    vendor\shmilyzxt\yii2-queue\jobs\jobs.sql##vendor\shmilyzxt\yii2-queue\failed\failed.sql
    2 sql files to the database to create a queue data table and a data table when the task fails.

  2. Push task start syntax:
  3. \Yii::$app-> ;queue->pushOn(new SendMial(),['email'=>'49783121@qq.com','title'=>'test','content'=>'email test'],' email');

    Let’s go to vendor\shmilyzxt\queue\queues\DatabaseQueue.php to take a look at the code. The pushOn() method is written in DatabaseQueueParent class of classvendor\shmilyzxt\queue\base\Queue.php中:

##
//入队列public function pushOn($job, $data = '', $queue = null)
    {        //canPush 检查队列是否已达最大任务量
        if ($this->canPush()) {  
            //beforePush 入队列前的事件
            $this->trigger(self::EVENT_BEFORE_PUSH); 
            //入队列
            $ret = $this->push($job, $data, $queue);
            //afterPush 入队列后的事件
            $this->trigger(self::EVENT_AFTER_PUSH);
            return $ret;
        } else {            throw new \Exception("max jobs number exceed! the max jobs number is {$this->maxJob}");
        }
    }
Copy after login

Comment: Here is the most Let’s take a look at the yii2 event event class.

About queuing:

$this->push($job, $data, $queue);

, here is the cooperation with

queue View class files, jump to related functions, process the data and record it in the database. (Function direction: getQueue()-->createPayload()-->pushToDatabase()),pushOn()Finally returns the result of data insertion into the database. Successful $ret is 1.3. Run the command processing queue in the background, for example: php ./ yii worker/listen default 10 128 3 0

where

default is the name of the queue. The email queue pushed above should be changed to email.After starting the command, let's look at the code: first execute: WorkerControllerController
actionListen method, we follow the code and enter vendor\shmilyzxt\queue\Worker.php -- In the listen method, it is actually looping all the time to execute the tasks of the operation queue: ##

/**  
 * 启用一个队列后台监听任务  
 * @param Queue $queue  
 * @param string $queueName 监听队列的名称(在pushon的时候把任务推送到哪个队列,则需要监听相应的队列才能获取任务)  
 * @param int $attempt 队列任务失败尝试次数,0为不限制  * @param int $memory 允许使用的最大内存  
 * @param int $sleep 每次检测的时间间隔  
 */
    public static function listen(Queue $queue, $queueName = 'default', $attempt = 10, $memory = 512, $sleep = 3, $delay = 0){        
        while (true){            
            try{               
                //DatabaseQueue从数据库队列取出一个可用任务(实例),并且更新任务
                $job = $queue->pop($queueName);
             }catch (\Exception $e){                
                throw $e;
                continue;
             }            
             if($job instanceof Job){                
                 //判断执行错误的次数是否大于传入的执行次数
                 if($attempt > 0 && $job->getAttempts() > $attempt){                    
                     $job->failed();
                 }else{                    
                     try{                        
                         //throw new \Exception("test failed");
                         $job->execute();
                      }catch (\Exception $e){                        
                          //执行失败,判断是否被删除,重新入队
                          if (! $job->isDeleted()) {                           
                              $job->release($delay);
                          }
                      }
                  }
               }else{                
                   self::sleep($sleep);
                }             
                if (self::memoryExceeded($memory)) {               
                    self::stop();
                }
               }
    }
Copy after login

Note: In

$queue->pop($ queueName);
is

vendor\shmilyzxt\queue\queues\DatabaseQueue.php

uses transactions to execute SQL within the method, and creates vendor\shmilyzxt\queue\jobs\DatabaseJob.php The instance of ##<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'> //取出一个任务 public function pop($queue = null) { $queue = $this-&gt;getQueue($queue); if (!is_null($this-&gt;expire)) { //$this-&gt;releaseJobsThatHaveBeenReservedTooLong($queue); } $tran = $this-&gt;connector-&gt;beginTransaction(); //判断是否有一个可用的任务需要执行 if ($job = $this-&gt;getNextAvailableJob($queue)) { $this-&gt;markJobAsReserved($job-&gt;id); $tran-&gt;commit(); $config = array_merge($this-&gt;jobEvent, [ &amp;#39;class&amp;#39; =&gt; &amp;#39;shmilyzxt\queue\jobs\DatabaseJob&amp;#39;, &amp;#39;queue&amp;#39; =&gt; $queue, &amp;#39;job&amp;#39; =&gt; $job, &amp;#39;queueInstance&amp;#39; =&gt; $this, ]); return \Yii::createObject($config); } $tran-&gt;commit(); return false; }</pre><div class="contentsignin">Copy after login</div></div> as for:

$job->execute();

is
DatabaseJob

inherits the parent class

Job Executed, follow the code to find the event executed by yii\base\Component trigger,<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>/** * 执行任务 */ public function execute(){ //beforeExecute 执行任务之前的一个事件 在JobEvent中并没有什么可执行的代码 $this-&gt;trigger(self::EVENT_BEFORE_EXECUTE, new JobEvent([&quot;job&quot; =&gt; $this, &amp;#39;payload&amp;#39; =&gt; $this-&gt;getPayload()])); $this-&gt;resolveAndFire();//真正执行的任务的方法 }</pre><div class="contentsignin">Copy after login</div></div>

 /**   * 真正任务执行方法(调用hander的handle方法)   * @param  array $payload   * @return void */
    protected function resolveAndFire()
    {        $payload = $this->getPayload();
        $payload = unserialize($payload); //反序列化数据
        $type = $payload[&#39;type&#39;];
        $class = $payload[&#39;job&#39;];

        if ($type == &#39;closure&#39; && ($closure = (new Serializer())->unserialize($class[1])) instanceof \Closure) {            
            $this->handler = $this->getHander($class[0]);
            $this->handler->closure = $closure;
            $this->handler->handle($this, $payload[&#39;data&#39;]);
        } else if ($type == &#39;classMethod&#39;) {            $payload[&#39;job&#39;][0]->$payload[&#39;job&#39;][1]($this, $payload[&#39;data&#39;]);
        } else if ($type == &#39;staticMethod&#39;) {            $payload[&#39;job&#39;][0]::$payload[&#39;job&#39;][1]($this, $payload[&#39;data&#39;]);
        } else {//执行的`SendMail`类的`handle($job,$data)`方法
            $this->handler = $this->getHander($class);
            $this->handler->handle($this, $payload[&#39;data&#39;]);
        }        //执行完任务后删除
        if (!$this->isDeletedOrReleased()) {            $this->delete();
        }
    }
Copy after login

Finally comes to the

handle($job,$data)

of the executed
SendMail

class. Here are the objects 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 &#39;<pre class="brush:php;toolbar:false">&#39;;print_r($payload);
        //$payload即任务的数据,你拿到任务数据后就可以执行发邮件了
        //TODO 发邮件
    }
Copy after login

The above is the detailed content of Introduction to PHPyii2 queue shmilyzxt/yii2-queue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

See all articles