https://hyperf.wiki/#/zh/rate-limit
composer require hyperf/rate-limit
<?php
namespace App\Controller;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\RateLimit\Annotation\RateLimit;
/**
* @Controller(prefix="rate-limit")
*/
class RateLimitController
{
/**
* @RequestMapping(path="test")
* @RateLimit(create=1, capacity=3)
*/
public function test()
{
return ["QPS 1, 峰值3"];
}
/**
* @RequestMapping(path="test2")
* @RateLimit(create=2, consume=2, capacity=4)
*/
public function test2()
{
return ["QPS 2, 峰值2"];
}
}
config/autoload/exceptions.php新增
App\Exception\Handler\RateLimitExceptionHandler::class
app/Exception/Handler/ 新建異常處理
<?php
namespace App\Exception\Handler;
use Hyperf\Di\Annotation\Inject;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Hyperf\RateLimit\Exception\RateLimitException;
use Throwable;
class RateLimitExceptionHandler extends ExceptionHandler
{
/**
* @Inject
*
* @var \Hyperf\HttpServer\Contract\ResponseInterface as httpResponse
*/
protected $httpResponse;
public function handle(Throwable $throwable, ResponseInterface $response)
{
// 判斷被捕獲到的異常是希望被捕獲的異常
if ($throwable instanceof RateLimitException) {
// 格式化輸出
$data = json_encode([
'code' => $throwable->getCode(),
'msg' => $throwable->getMessage(),
], JSON_UNESCAPED_UNICODE);
// 阻止異常冒泡
$this->stopPropagation();
// return $response->withStatus(500)->withBody(new SwooleStream($data));
return $this->httpResponse->json(['msg' => '觸發訪問頻率限制', 'code' => 503, 'data' => $data]);
}
// 交給下一個異常處理器
return $response;
// 或者不做處理直接遮蔽異常
}
/**
* 判斷該異常處理器是否要對該異常進行處理
*/
public function isValid(Throwable $throwable): bool
{
return true;
}
}
- 自定義異常請看官方異常處理章節
https://hyperf.wiki/#/zh/exception-handler