首页 > 解决方案 > Laravel 中的批量用户通知

问题描述

我有一个使用 Laravel 创建的应用程序。有时我需要向我的用户发送通知(通过数据库)。

问题:每当我向所有用户(~15k)说通知时,我的应用程序就会停止工作。有什么办法可以批处理这个过程吗?

我正在使用 livewire 组件发送通知。当我向特定用户发送通知时,它没有问题。但是,当我向所有用户发送通知时,我的应用程序会冻结。

// livewire component
Notification::send($users, new \App\Notifications\SendNotification($this->title, $this->message));

这是我的 SendNotification.php

<?php

namespace App\Notifications;

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

class SendNotification extends Notification implements ShouldQueue
{
    use Queueable;

    protected $title;
    protected $message;

    /**
     * Create a new notification instance.
     *
     * @param $title
     * @param $message
     */
    public function __construct($title, $message)
    {
        $this->title = $title;
        $this->message = $message;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    public function toDatabase($notifiable)
    {
        return [
            'title' => $this->title,
            'message' => $this->message,
        ];
    }
}

标签: phplaravel

解决方案


也许你可以试试这个

$when = now()->addSecond();
\Notification::send($users, (new \App\Notifications\SendNotification($this->title, $this->message))->delay($when));

推荐阅读