我在 Laravel 9 中为 Job 设置限制时遇到问题。
我想为任务设置限制,考虑到用户。
我按照文档中的说明进行操作。
第一步。在提供程序中,我为每个用户设置了每分钟限制(我将用户 ID 设置为键)
namespace App\Providers;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->register(RepositoryServiceProvider::class);
$this->app->register(RequestValidationProvider::class);
$this->app->register(CustomServiceProvider::class);
}
public function boot(): void
{
RateLimiter::for('Limiter', function (object $job) {
Log::info($job->userId);
return Limit::perMinute(10)->by($job->userId)->response(function() {
Log::info('Too many attempts!');
});
});
}
}
下一步是向任务本身添加一个中间件方法,其名称与我们在
RateLimiter
.中创建的
AppServiceProvider
同名
这是职位代码。
namespace App\Jobs;
use App\Services\Crm\ServiceFactory;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\Middleware\RateLimitedWithRedis;
class SendEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
private readonly string $crmSlug,
private readonly array $email,
public readonly int $userId
){}
public function handle(ServiceFactory $serviceFactory): void
{
$service = $serviceFactory->get($this->slug);
$service->sendEmail($this->email);
}
public function middleware(): array
{
Log::info(json_encode(new RateLimitedWithRedis('Limiter')));
return [new RateLimitedWithRedis('Limiter')];
}
}
没有错误。但是任务和以前一样执行,没有考虑限制。
这是日志。
这是
queue.php
谁能帮我解决这个问题?
你可以试试这个spatie包 spatie/laravel-rate-limited-job-middleware