Skip to content

Commit 5e8cf40

Browse files
committed
ratelimit doc
1 parent 12bac82 commit 5e8cf40

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

doc/ratelimit.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
## Ratelimit
3+
4+
```php
5+
<?php
6+
declare(strict_types=1);
7+
8+
9+
namespace App\Middleware;
10+
11+
12+
use App\Exception\RuntimeException;
13+
use App\Utils\Json;
14+
use Closure;
15+
use DcrSwoole\Log\LogBase;
16+
use DcrSwoole\RateLimit\RateLimitHandler;
17+
use DcrSwoole\Request\Request;
18+
use DcrSwoole\Response\Response;
19+
use DcrSwoole\Utils\ApplicationContext;
20+
21+
class RateLimitMiddleware
22+
{
23+
public function handle(): Closure
24+
{
25+
return static function ($request, $next) {
26+
$throttler = ApplicationContext::getContainer()->get(RateLimitHandler::class);
27+
// “桶”可以容纳的请求数
28+
$capacity = 60;
29+
// “桶”完全重新装满所需的时间
30+
$seconds = 60;
31+
// “桶”此操作使用的令牌数
32+
$cost = 1;
33+
34+
if ($throttler->handle($request->getRemoteIp(), $capacity, $seconds, $cost) === false) {
35+
throw new RuntimeException('请求次数太频繁');
36+
}
37+
38+
return $next->handle($request);
39+
};
40+
41+
}
42+
}
43+
```

0 commit comments

Comments
 (0)