限制 Laravel 中的排队作业
Limit Queued Job in Laravel
我有一个电子邮件服务,它允许我每小时(1 次/分钟)仅发送 60 封电子邮件。
所以这就是为什么我要尝试编写一个遵守服务提供商限制的应用程序,
我正在通过队列作业一次向批量用户发送电子邮件,请看一下代码
public function sendEmails(CreateEmailRequest $request)
{
$data = [];
$users = User::find($request->to);
$subject = $request->subject;
$body = $this->fileUpload($request->body);
foreach ($users as $user) {
$vars = array(
"{{name}}" => $user->name,
"{{email}}" => $user->email,
);
$body = strtr($body, $vars);
$data['body'] = $body;
$data['user'] = $user;
$data['subject'] = $subject;
dispatch(new SendEmailJob($data))->onQueue('mail');
}
Flash::success('Email sent successfully.');
return redirect(route('emails.index'));
}
这里是 SendEmailJob Class 代码
public function handle()
{
$data = $this->data;
$body = $data['body'];
$user = $data['user'];
$subject = $data['subject'];
// list($body, $user, $subject) = $this->data;
Mail::send('mail.email', ['body' => $body], function ($m) use ($user, $subject) {
$m->to($user->email)->subject($subject);
});
}
public function middleware()
{
return Limit::perMinute(1);
}
当我 运行 php artisan queue:work 它一次处理所有作业..
你能告诉我我怎样才能做到这一点吗?
我不能使用 spatie/laravel-rate-limited-job-middleware 因为我的服务器不支持 Redis。
你能告诉我我做错了吗?
您可以将作业中间件与 rate limiting
在您的 AppServiceProvider 的启动方法中
RateLimiter::for('emails', function($job) {
return Limit::perMinute(1);
});
并将中间件添加到作业中:
use Illuminate\Queue\Middleware\RateLimited;
public function middleware()
{
return [new RateLimited('emails')];
}
我有一个电子邮件服务,它允许我每小时(1 次/分钟)仅发送 60 封电子邮件。 所以这就是为什么我要尝试编写一个遵守服务提供商限制的应用程序, 我正在通过队列作业一次向批量用户发送电子邮件,请看一下代码
public function sendEmails(CreateEmailRequest $request)
{
$data = [];
$users = User::find($request->to);
$subject = $request->subject;
$body = $this->fileUpload($request->body);
foreach ($users as $user) {
$vars = array(
"{{name}}" => $user->name,
"{{email}}" => $user->email,
);
$body = strtr($body, $vars);
$data['body'] = $body;
$data['user'] = $user;
$data['subject'] = $subject;
dispatch(new SendEmailJob($data))->onQueue('mail');
}
Flash::success('Email sent successfully.');
return redirect(route('emails.index'));
}
这里是 SendEmailJob Class 代码
public function handle()
{
$data = $this->data;
$body = $data['body'];
$user = $data['user'];
$subject = $data['subject'];
// list($body, $user, $subject) = $this->data;
Mail::send('mail.email', ['body' => $body], function ($m) use ($user, $subject) {
$m->to($user->email)->subject($subject);
});
}
public function middleware()
{
return Limit::perMinute(1);
}
当我 运行 php artisan queue:work 它一次处理所有作业.. 你能告诉我我怎样才能做到这一点吗? 我不能使用 spatie/laravel-rate-limited-job-middleware 因为我的服务器不支持 Redis。 你能告诉我我做错了吗?
您可以将作业中间件与 rate limiting
在您的 AppServiceProvider 的启动方法中
RateLimiter::for('emails', function($job) {
return Limit::perMinute(1);
});
并将中间件添加到作业中:
use Illuminate\Queue\Middleware\RateLimited;
public function middleware()
{
return [new RateLimited('emails')];
}