-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
<?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); | ||
}; | ||
|
||
} | ||
} |