Skip to content

Commit 78d0d1b

Browse files
committed
自定义限流键
1 parent e95fd27 commit 78d0d1b

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,15 @@ Tinywan\LimitTraffic\RateLimiter::getRateLimit(); // 返回 [100, 600]
7373

7474
编辑 `config/plugin/tinywan/limit-traffic/app.php` 文件的 `status` HTTP 状态码(默认值是 `429`
7575

76+
### 自定义限流键
77+
78+
编辑 `config/plugin/tinywan/limit-traffic/app.php` 文件的 `limit_key` 限流键(默认值是 `none`
79+
80+
- `none 代表以ip作为限流键`
81+
- `get.id 代表以get请求的id作为限流键`
82+
- `post.access 代表以post请求的access作为限流键`
83+
- `header.token 代表以header请求的token作为限流键`
84+
7685
### 自定义`body`返回内容
7786

7887
编辑 `config/plugin/tinywan/limit-traffic/app.php` 文件的 `body` 的字段

src/RateLimiter.php

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public static function traffic()
4141
$scriptSha = Redis::script('load', $script);
4242
Redis::set(self::LIMIT_TRAFFIC_SCRIPT_SHA, $scriptSha);
4343
}
44-
$limitKey = self::LIMIT_TRAFFIC_PRE . request()->getRealIp();
44+
$limitKey = self::getLimitKey($config);
4545
$result = Redis::rawCommand('evalsha', $scriptSha, 1, $limitKey, $config['limit'], $config['window_time']);
4646
if ($result === 0) {
4747
return [
@@ -64,4 +64,35 @@ public static function getRateLimit(): array
6464
$config = config('plugin.tinywan.limit-traffic.app.limit');
6565
return [$config['limit'], $config['window_time']];
6666
}
67+
68+
/**
69+
* @desc: 获取限流key
70+
* @author kylin987
71+
*/
72+
private static function getLimitKey($config): string
73+
{
74+
$limitKey = $config['limit_key'] ?? '';
75+
// 默认按 IP 限流
76+
if (empty($limitKey) || $limitKey === 'none') {
77+
return self::LIMIT_TRAFFIC_PRE . md5(request()->getRealIp());
78+
}
79+
// 按 "来源.字段名" 拆分
80+
[$source, $key] = explode('.', $limitKey . '.', 2);
81+
82+
switch (strtolower($source)) {
83+
case 'get':
84+
$keyValue = request()->get($key, 'none');
85+
break;
86+
case 'post':
87+
$keyValue = request()->post($key, 'none');
88+
break;
89+
case 'header':
90+
$keyValue = request()->header($key, 'none');
91+
break;
92+
default:
93+
// fallback:IP
94+
$keyValue = request()->getRealIp();
95+
}
96+
return self::LIMIT_TRAFFIC_PRE . md5($keyValue);
97+
}
6798
}

src/config/plugin/tinywan/limit-traffic/app.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
return [
44
'enable' => true,
55
'limit' => [
6+
'limit_key' => 'none', // none:以ip地址为限流键,'get.id','header.X-Token','post.user_id',也可以自定义限流键
67
'limit' => 10, // 请求次数
78
'window_time' => 60, // 窗口时间,单位:秒
89
'status' => 429, // HTTP 状态码

0 commit comments

Comments
 (0)