<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* RateLimitCheck.php
|
|
* Created by PhpStorm.
|
|
* Date: 2026/10/17
|
|
* Time: 09:40
|
|
* Author: qian.guo
|
|
* E-mail: yiyezhiqiutel@gmail.com
|
|
*/
|
|
|
|
namespace app\middleware;
|
|
|
|
use Closure;
|
|
use think\facade\Cache;
|
|
use think\Request;
|
|
|
|
/**
|
|
* 固定窗口限流中间件
|
|
* 设计说明:
|
|
* - 用法(路由里传参):->middleware(RateLimitCheck::class, 'auth_login', 20, 60)
|
|
* 参数顺序:场景名、窗口内允许次数、窗口秒数
|
|
* - 身份取 account_id 优先、否则取 IP:登录前接口只能按 IP 限,防止刷登录
|
|
* 登录后按账号限,避免同一办公网段互相误伤
|
|
* - 存储跟着 config('cache.default') 走,不写死 redis
|
|
* 若写死 redis,在未接入 redis 的环境一调接口就抛「未配置 store: redis」,直接把功能堵死
|
|
*
|
|
* ⚠️ file 驱动下的 inc() 是「读-改-写」,并发下会丢计数,只可用于开发
|
|
* 生产必须切 Redis(其 INCR 是原子的),否则限流在压测下形同虚设
|
|
*/
|
|
class RateLimitCheck
|
|
{
|
|
public function handle(Request $request, Closure $next, $scene = 'default', $limit = 60, $window = 60)
|
|
{
|
|
$limit = intval($limit);
|
|
if ($limit < 1) {
|
|
return $next($request);
|
|
}
|
|
|
|
$cache = Cache::store();
|
|
$key = 'rl:' . $scene . ':' . $this->getIdentity($request);
|
|
|
|
$count = intval($cache->inc($key));
|
|
|
|
// inc 在键不存在时以 1 创建且不带过期时间,此时补写一次以带上 TTL
|
|
// 用 set 而不是 expire():少依赖一个驱动方法,语义也更直白
|
|
if ($count === 1) {
|
|
$cache->set($key, 1, intval($window));
|
|
}
|
|
|
|
if ($count > $limit) {
|
|
return json([
|
|
'code' => config('code.fail'),
|
|
'msg' => '操作过于频繁,请稍后再试'
|
|
]);
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
|
|
/**
|
|
* 取限流身份
|
|
* getIdentity
|
|
* @param Request $request 请求对象
|
|
* @return string
|
|
*/
|
|
private function getIdentity(Request $request)
|
|
{
|
|
$account_id = LoginCheck::accountId();
|
|
if ($account_id > 0) {
|
|
return 'u' . $account_id;
|
|
}
|
|
|
|
return 'ip' . md5($request->ip());
|
|
}
|
|
}
|