繁体   English   中英

如何处理队列超时的大量邮件发送

[英]How to handle mass mail sending with queue timeout

我有 10 万多封电子邮件的表格,我想每天发送一些 email:

我在 app\Console\Kernel.php 中添加了时间表:

$schedule->job(new SendDailyEmails)->dailyAt('09:00');

内部工作我有:

$users = User::all();
foreach($users as $user){
    Maill:to($user->email)->send(new DailyMail($user));
    $status = 'sent';
    if( in_array($user->email, Mail::failures()) ){
        $status = 'failed';
        Log::error($user->email . ' was not sent.');
    }else{
        Log::info($user->email . ' was sent.');
    }
    SentMail::create([
        'email' => $user->email,
        'status' => $status
    ]);

}

这工作正常,但一段时间后这可能会因为作业超时而停止。 在 failed_jobs 表中,我收到MaxAttemptsExceededException消息,提示 Job 尝试了太多次或运行时间过长。 由于我在主管中将队列尝试最多设置为 3,因此它应该只执行 go 3 次。 通过测试它并没有尝试再次尝试,因为我收到了一封邮件而不是 3 封。

所以到了超时,我不确定默认值是什么,但这有关系吗,因为我不知道发送所有电子邮件需要多少时间?

我应该将邮件分成 50 个一组并为每个组调用单独的作业实例吗?

有人对此有很好的工作答案吗?

如果您查看官方文档,您会发现每封邮件都可以排队。

所以,你应该从

Mail:to($user->email)->send(new DailyMail($user));

Mail:to($user->email)->queue(new DailyMail($user));

通过这种方式,您将工作生成的每封邮件都推入队列。 我建议您创建一个特定的队列并使用像laravel 地平线这样的系统,以便更好地监控。

还要记住分块和延迟发送,因为您的应用程序可能会运行超时错误,而且如果像mailgun这样的提供商看到异常活动,他们可能会阻止您的发送。

与其尝试在 class 中一次发送 100k+ 封电子邮件,不如将 100k+ 作业实例分派给队列工作者

$users = User::all();
foreach($users as $user){
  $schedule->job(new SendDailyEmails($user))->dailyAt('09:00');
}

现在Laravel将在队列中堆叠 100k+ 个作业,并尝试一次为每个用户发送一个 email

class SendDailyEmails implements ShouldQueue
{
  public $user;

  public function __construct(User $user)
  {
    $this->user = $user;
  }

  Maill:to($this->user->email)->send(new DailyMail($user));
    $status = 'sent';
    if( in_array($this->user->email, Mail::failures()) ){
        $status = 'failed';
        Log::error($this->user->email . ' was not sent.');
    }else{
        Log::info($this->user->email . ' was sent.');
    }
    SentMail::create([
        'email' => $this->user->email,
        'status' => $status
    ]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM