イントロダクションIntroduction
Laravelには、簡単に使用できるレート制限の抽象化機能があり、アプリケーションのcacheと連携して、指定した時間帯のアクションを制限する簡単な方法を提供します。Laravel includes a simple to use rate limiting abstraction which, in conjunction with your application's cache[cache], provides an easy way to limit any action during a specified window of time.
レート制限ミドルウェアのドキュメントを参照してください。[!NOTE]
Note: 受信HTTPリクエストのレートを制限したい場合は、
If you are interested in rate limiting incoming HTTP requests, please consult the rate limiter middleware documentation[routing#rate-limiting].
キャッシュ設定Cache Configuration
通常、レート制限では、アプリケーションのcache
設定ファイルのdefault
キーで定義されているデフォルトのアプリケーションキャッシュを使用します。しかし、アプリケーションのcache
設定ファイル内でlimiter
キーを定義すれば、レート制限で使用するキャッシュドライバを指定できます。Typically, the rate limiter
utilizes your default application cache as defined
by the default
key within your
application's cache
configuration file.
However, you may specify which cache driver the rate
limiter should use by defining a
limiter
key within your application's
cache
configuration file:
'default' => env('CACHE_STORE', 'database'),
'limiter' => 'redis',
基本の使い方Basic Usage
Illuminate\Support\Facades\RateLimiter
ファサードを使って、レート制限を操作できます。レート制限が提供する最もシンプルなメソッドはattempt
メソッドで、これは指定されたコールバックを指定された秒数でレート制限するものです。The
Illuminate\Support\Facades\RateLimiter
facade may be used to interact with the rate
limiter. The simplest method offered by the rate
limiter is the attempt
method, which
rate limits a given callback for a given number of
seconds.
attempt
メソッドは、コールバックで利用できる残り試行回数がない場合は、false
を返し、そうでない場合には、attempt
メソッドはコールバックの結果、またはtrue
を返します。attempt`メソッドが受け付ける最初の引数は、レート制限の「キー」で、レート制限をかけるアクションを表す任意の文字列を指定します。The attempt
method
returns false
when the callback has no
remaining attempts available; otherwise, the
attempt
method will return the
callback's result or true
. The first
argument accepted by the attempt
method
is a rate limiter "key", which may be any
string of your choosing that represents the action
being rate limited:
use Illuminate\Support\Facades\RateLimiter;
$executed = RateLimiter::attempt(
'send-message:'.$user->id,
$perMinute = 5,
function() {
// メッセージ送信…
}
);
if (! $executed) {
return 'Too many messages sent!';
}
必要であれば、attempt
メソッドに第4引数を与えられます。これは「減衰率」、または試行が利用可能になるまでのリセット秒数です。例として、上記のサンプルコードを修正して、2分ごとに5回の試行するようにしてみます。If necessary, you may provide a
fourth argument to the attempt
method,
which is the "decay rate", or the number
of seconds until the available attempts are reset.
For example, we can modify the example above to
allow five attempts every two minutes:
$executed = RateLimiter::attempt(
'send-message:'.$user->id,
$perTwoMinutes = 5,
function() {
// メッセージ送信…
},
$decayRate = 120,
);
試行回数の手作業増加Manually Incrementing Attempts
レート制限を手作業で操作する場合は、他にもさまざまな方法があります。たとえば、tooManyAttempts
メソッドを呼び出して、指定したレート制限キーが1分間に許可した最大試行回数を超えたかを判断できます。If you would like to manually
interact with the rate limiter, a variety of other
methods are available. For example, you may invoke
the tooManyAttempts
method to determine
if a given rate limiter key has exceeded its maximum
number of allowed attempts per minute:
use Illuminate\Support\Facades\RateLimiter;
if (RateLimiter::tooManyAttempts('send-message:'.$user->id, $perMinute = 5)) {
return 'Too many attempts!';
}
RateLimiter::increment('send-message:'.$user->id);
// メッセージ送信処理…
他にも、remaining
メソッドを使って、指定キーの残りの試行回数を取得することも可能です。指定キーに再試行回数が残っている場合は、increment
メソッドを呼び出して総試行回数を増やせます。Alternatively, you may use the
remaining
method to retrieve the number
of attempts remaining for a given key. If a given
key has retries remaining, you may invoke the
increment
method to increment the
number of total attempts:
use Illuminate\Support\Facades\RateLimiter;
if (RateLimiter::remaining('send-message:'.$user->id, $perMinute = 5)) {
RateLimiter::increment('send-message:'.$user->id);
// メッセージ送信処理…
}
指定するレートリミッターキーの値を1以上増やしたい場合は、increment
メソッドへ希望する量を指定してください。If you would like to increment
the value for a given rate limiter key by more than
one, you may provide the desired amount to the
increment
method:
RateLimiter::increment('send-message:'.$user->id, amount: 5);
使用可能時間の判断Determining Limiter Availability
キーの試行回数がなくなると、availableIn
メソッドは試行回数が増えるまでの残り秒数を返します。When a key has no more attempts
left, the availableIn
method returns
the number of seconds remaining until more attempts
will be available:
use Illuminate\Support\Facades\RateLimiter;
if (RateLimiter::tooManyAttempts('send-message:'.$user->id, $perMinute = 5)) {
$seconds = RateLimiter::availableIn('send-message:'.$user->id);
return 'You may try again in '.$seconds.' seconds.';
}
RateLimiter::increment('send-message:'.$user->id);
// メッセージ送信処理…
試行のクリアClearing Attempts
clear
メソッドを使って、任意のレート制限キーの試行回数をリセットできます。例えば、指定メッセージが受信者によって読まれたときに試行回数をリセットできます。You may reset the number of
attempts for a given rate limiter key using the
clear
method. For example, you may
reset the number of attempts when a given message is
read by the receiver:
use App\Models\Message;
use Illuminate\Support\Facades\RateLimiter;
/**
* メッセージを既読としてマーク
*/
public function read(Message $message): Message
{
$message->markAsRead();
RateLimiter::clear('send-message:'.$message->user_id);
return $message;
}