Laravel 通知外观队列响应时间

Laravel Notification Facade Queue Response Time

Laravel 文档解释说,当 dispatching/sending 通知时,您可能希望将它们排队以加快应用程序响应时间。

https://laravel.com/docs/5.5/notifications#queueing-notifications

这正是我想要做的,但是我使用通知外观而不是可通知特征来调用它。我担心前者会绕过队列,我需要它一次通知一组用户。

正如文档中所说:

Alternatively, you may send notifications via the Notification facade. This is useful primarily when you need to send a notification to multiple notifiable entities such as a collection of users.

但是当我通过 facade 调用我的 Notification 时,它不会排队。我知道这一点是因为当我监控我的网络请求并注释掉外观调用时,我的请求从 2 多秒(通过通知调用)变为不到 .5 秒(当我将其注释掉时)。

这是我使用队列 (NewAsset) 通知 class 的开始:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class NewAsset extends Notification implements ShouldQueue
{
    use Queueable;

调用如下:

$asset = new Asset;
$asset->user_id = Auth::user()->id;
$asset->type = "Text";
$asset->content = $content;
$asset->forum_id = 1;
$asset->save();
$users = User::where("id","!=",Auth::user()->id)->get();
Notification::send($users, new NewAsset($asset,Auth::user()));
//if i comment out the notification call above, response time decreases dramatically 
return;

我做错了什么?

哦...好像是在触发队列:

php artisan queue:listen
[2018-03-31 15:48:22] Processing: App\Notifications\NewAsset
[2018-03-31 15:48:22] Processed:  App\Notifications\NewAsset
[2018-03-31 15:48:23] Processing: App\Notifications\NewAsset
[2018-03-31 15:48:23] Processed:  App\Notifications\NewAsset
[2018-03-31 15:48:24] Processing: App\Notifications\NewAsset
[2018-03-31 15:48:24] Processed:  App\Notifications\NewAsset
[2018-03-31 15:48:25] Processing: App\Notifications\NewAsset
[2018-03-31 15:48:25] Processed:  App\Notifications\NewAsset

那为什么这么慢? :(

Notification::send 很慢(> 2 秒),有可能,您有数千个可通知实体推送到数据库队列,这很慢,因为数以千计的插入语句在数据库上执行。要改进,您可以:

  1. 使用其他队列驱动程序,例如 Amazon SQS、Beanstalkd、Redis 等。它们针对低延迟的工作队列进行了优化。与作为工作队列的数据库相比,它们快如闪电。

  2. 再创建一个job,让worker排队所有的通知,例如:

    php artisan make:job QueueUserNotificationsJob
    

    YourController.php

    dispatch(new QueueUserNotificationsJob(Auth::user()->id));
    

    QueueUserNotificationsJob.php

    public $authUserId = null;
    
    public function __construct($authUserId) {
    
        $this->authUserId = $authUserId;
    
    }
    
    public function handle() {
    
        $users = User::where("id", "!=", $this->authUserId)->get();
    
        Notification::send($users, new NewAsset($asset, $this->authUserId));
    
    }