@@ -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}
0 commit comments