Skip to content

Commit

Permalink
ratelimit doc
Browse files Browse the repository at this point in the history
  • Loading branch information
guanhui07 committed Feb 13, 2023
1 parent 12bac82 commit 5e8cf40
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions doc/ratelimit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@

## Ratelimit

```php
<?php
declare(strict_types=1);


namespace App\Middleware;


use App\Exception\RuntimeException;
use App\Utils\Json;
use Closure;
use DcrSwoole\Log\LogBase;
use DcrSwoole\RateLimit\RateLimitHandler;
use DcrSwoole\Request\Request;
use DcrSwoole\Response\Response;
use DcrSwoole\Utils\ApplicationContext;

class RateLimitMiddleware
{
public function handle(): Closure
{
return static function ($request, $next) {
$throttler = ApplicationContext::getContainer()->get(RateLimitHandler::class);
// “桶”可以容纳的请求数
$capacity = 60;
// “桶”完全重新装满所需的时间
$seconds = 60;
// “桶”此操作使用的令牌数
$cost = 1;

if ($throttler->handle($request->getRemoteIp(), $capacity, $seconds, $cost) === false) {
throw new RuntimeException('请求次数太频繁');
}

return $next->handle($request);
};

}
}
```

0 comments on commit 5e8cf40

Please sign in to comment.