我的應(yīng)用程序托管在共享托管平臺(tái)上,該平臺(tái)限制每小時(shí) 200 封電子郵件。
我的應(yīng)用程序正在運(yùn)行數(shù)據(jù)庫連接驅(qū)動(dòng)程序,并且作業(yè)表中有 3000 個(gè)作業(yè)。
我想限制此隊(duì)列,使其每 30 秒或 1 分鐘僅發(fā)送 1 封電子郵件,以確保我的托管不會(huì)出現(xiàn)問題。
研究: 我嘗試過本教程的延遲、此問題的速率限制但沒有響應(yīng)、此 laravel 文檔的延遲作業(yè),但沒有任何效果。
問題:有沒有辦法像在redis隊(duì)列連接中那樣限制數(shù)據(jù)庫隊(duì)列連接中的隊(duì)列,即
// Allow only 1 email every 30 seconds Redis::throttle('any_key')->allow(1)->every(30)->then(function () { Mail::to($this->email)->send(new NotificationEmail($this->data) ); Log::info('Emailed order ' . $this->email); }, function () { // Could not obtain lock; this job will be re-queued return $this->release(2); });
我的實(shí)現(xiàn):僅延遲第一個(gè)作業(yè),然后立即發(fā)送其他作業(yè)
public function sendEmailNotification($email,$data) { //Send email to user and to admin $email_job = (new ProcessEmailNotificationJob($email,$data))->delay(now()->addSeconds(30)); if($this->dispatch($email_job)){ return true; } else{ return false; } }
**ENV 文件:**
BROADCAST_DRIVER=log CACHE_DRIVER=file QUEUE_CONNECTION=database SESSION_DRIVER=file SESSION_LIFETIME=120 MEMCACHED_HOST=127.0.0.1
你運(yùn)行php artisanqueue:listen了嗎,如果是,請檢查我下面的代碼也許會(huì)有幫助
在控制器內(nèi):
$mail = ( [ 'data' => $EmailData, 'userName' => $userData->first_name, 'userMail' => $userData->email, 'subject' => $subject ]); SendMailJob::dispatch($mail) ->delay(now()->addSeconds($waitSec)); $waitSec += 30; //seconds interval
SendMailJob 類
namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use App\Mail\ClientRegistrationNotification; use Mail; class SendMailJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $bulkMail, $mail; public function __construct($Mail) { $this->mail=$Mail; } public function handle() { try { Mail::to($this->mail['userMail']) ->queue(new ClientRegistrationNotification($this->mail['data'], $this->mail['userName'], $this->mail['userMail'], $this->mail['subject'])); } catch (\Throwable $exception) { $this->fail(); } } }