问题描述
有人知道有一种方法可以限制Laravel中某些异常的电子邮件通知吗?
当数据库出现错误时,我通过检查QueryException
使我的应用向我发送电子邮件。这是我在Laravel中的异常处理程序中所做的一个粗略示例:
class Handler{
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry,Bugsnag,etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $e)
{
if($e instanceof QueryException){
if( App::environment(['production']) ){
Notification::route('mail','myemail@test.com')
->notify(new DbErrorNotification($e));
}
}
parent::report($e);
}
}
数据库中的跟踪功能很短,是否有一种方法可以按异常类型限制数据库错误,以免在出现一致的数据库错误时最终不会收到数千封电子邮件。
我查看了Swift Mailer's anti-flood and throttling个插件,但是这些插件会全局影响我不想做的系统。
提前谢谢
解决方法
有几种方法可以实现这一目标。在分派作业之前,您可以在其上添加delay
。示例:
use App\Http\Request;
use App\Jobs\SendEmail;
use App\Mail\VerifyEmail;
use Carbon\Carbon;
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return \Illuminate\Http\RedirectResponse
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function store(Request $request)
{
$baseDelay = json_encode(now());
$getDelay = json_encode(
cache('jobs.' . SendEmail::class,$baseDelay)
);
$setDelay = Carbon::parse(
$getDelay->date
)->addSeconds(10);
cache([
'jobs.' . SendEmail::class => json_encode($setDelay)
],5);
SendEmail::dispatch($user,new VerifyEmail($user))
->delay($setDelayTime);
}
或者,如果您不喜欢关于工作的想法,也可以通过Mail
来延迟它。示例:
Mail::to($user)->later($setDelayTime);
最后通过Redis速率限制。示例:
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Redis::throttle('SendEmail')
->allow(1)
->every(10)
->then(function () {
Mail::to($this->user)->send($this->mail);
},function () {
return $this->release(10);
});
}
允许每十秒钟发送一封电子邮件。传递给节流()方法的字符串SendEmail是唯一标识受速率限制的作业类型的名称。您可以将其设置为任何您想要的。
release()方法是您的作业类的继承成员,并且 指示Laravel将作业释放回队列, 如果无法获得锁,则以秒为单位的可选延迟。 当作业被分派到队列时,Redis被指示仅 每十秒钟运行一次SendEmail作业。
请记住,为此,您需要一个 Redis
来源:https://medium.com/@bastones/a-simple-guide-to-queuing-mail-in-laravel-f4ff94cdaa59