This commit is contained in:
gr
2026-09-24 09:45:44 +08:00
parent dbf474ddd7
commit bd22e5f476
38 changed files with 19152 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace app\mcp\service;
use think\facade\Cache;
/**
* 基于系统缓存的固定窗口限流(缓存驱动为 redis 时计数更准确;文件缓存下为近似值)。
*/
class RateLimiter
{
/** 记一次并判断是否仍在限额内 */
public static function hit(string $key, int $limit, int $windowSeconds): bool
{
$bucket = 'ai_mcp_rl_' . $key . '_' . intdiv(time(), $windowSeconds);
$count = (int) Cache::get($bucket, 0) + 1;
Cache::set($bucket, $count, $windowSeconds * 2);
return $count <= $limit;
}
public static function rowsToday(int $adminId): int
{
return (int) Cache::get(self::rowsKey($adminId), 0);
}
public static function addRows(int $adminId, int $rows): void
{
if ($rows <= 0) {
return;
}
Cache::set(self::rowsKey($adminId), self::rowsToday($adminId) + $rows, 90000);
}
private static function rowsKey(int $adminId): string
{
return 'ai_mcp_rows_' . $adminId . '_' . date('Ymd');
}
}