Laravel Queues 队列代码示例

Laravel

当我们使用队列时
当你用很多需要消耗进程的请求时,可以使用队列来解决问题

开始

创建队列表

php artisan queue:table
php artisan migrate

在config->queue中找到 QUEUE_CONNECTION 更改如下

QUEUE_CONNECTION=database 

创建job类

php artisan make:job SendMail

修改job类如下

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendMail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $title;
    private $body;
    private $to;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($title, $body, $to)
    {
        $this->title = $title;
        $this->body = $body;
        $this->to = $to;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        echo "Start sending email".PHP_EOL;
        sleep(2);
        echo "Email sended to {$this->to}".PHP_EOL;
    }
}

使用dispatch方法分发任务

SendMail::dispatch("hi","how are you","alex@gmail.com");

现在只需要启动你的队列

php artisan queue:work

或者

php artisan queue:listen

如何你想知道上面量两种启动队列的方法有谁能不同,可以阅读下面的文章

「或者, 你可以运行 queue:listen 命令. 当使用 queue:listen 命令时, 当你想要重新加载已更新的代码或者重置程序时,你不需要重新启动队列。然而, 这个命令的运行效率不如 queue:work 」

之后你就可以看到下面内容

[2020-06-16 17:04:08][161] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:10][161] Processed:  App\Jobs\SendMail
[2020-06-16 17:04:10][162] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:12][162] Processed:  App\Jobs\SendMail
[2020-06-16 17:04:12][163] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:14][163] Processed:  App\Jobs\SendMail
[2020-06-16 17:04:14][164] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:16][164] Processed:  App\Jobs\SendMail
[2020-06-16 17:04:16][165] Processing: App\Jobs\SendMail
Start sending email
Email sended to alex@gmail.com
[2020-06-16 17:04:18][165] Processed:  App\Jobs\SendMail

好了
请随意提问!

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/azibom/laravel-queues-3ee...

译文地址:https://learnku.com/laravel/t/46593

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 1

谢谢楼主!
有一问题请教,我想把服务器上的这两个queue进程停掉,有什么方法呢,因为耗尽了CPU,而且PID不断在变,kill -9 PID 方法也没用,重启reboot 也没有停。
非常谢谢!

file

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!