Skip to content

Commit

Permalink
rate_limit
Browse files Browse the repository at this point in the history
  • Loading branch information
guanhui07 committed Feb 9, 2023
1 parent 68579dd commit 46b6392
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
38 changes: 38 additions & 0 deletions dcr/RateLimit/Middleware/RateLimitMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);


namespace DcrSwoole\RateLimit\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);
};

}
}
1 change: 1 addition & 0 deletions dcr/RateLimit/RateLimitHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ private function time(): int
/**
* Used during testing to set the current timestamp to use.
*
* @param int $time
* @return $this
*/
public function setTestTime(int $time): self
Expand Down

0 comments on commit 46b6392

Please sign in to comment.