;rgb:0000/0000/0000

gengx
This commit is contained in:
gr
2026-09-24 11:03:44 +08:00
parent bd22e5f476
commit 68fc86a167
10 changed files with 1257 additions and 34 deletions
+23 -6
View File
@@ -4,24 +4,37 @@ declare(strict_types=1);
namespace app\mcp\service;
use think\facade\Cache;
use think\facade\Log;
/**
* 基于系统缓存的固定窗口限流(缓存驱动为 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;
try {
$bucket = 'ai_mcp_rl_' . $key . '_' . intdiv(time(), $windowSeconds);
$count = (int) Cache::get($bucket, 0) + 1;
Cache::set($bucket, $count, $windowSeconds * 2);
return $count <= $limit;
} catch (\Throwable $e) {
Log::warning('[ai_mcp] 限流计数失败,本次放行: ' . $e->getMessage());
return true;
}
}
public static function rowsToday(int $adminId): int
{
return (int) Cache::get(self::rowsKey($adminId), 0);
try {
return (int) Cache::get(self::rowsKey($adminId), 0);
} catch (\Throwable $e) {
Log::warning('[ai_mcp] 读取今日行数失败: ' . $e->getMessage());
return 0;
}
}
public static function addRows(int $adminId, int $rows): void
@@ -29,7 +42,11 @@ class RateLimiter
if ($rows <= 0) {
return;
}
Cache::set(self::rowsKey($adminId), self::rowsToday($adminId) + $rows, 90000);
try {
Cache::set(self::rowsKey($adminId), self::rowsToday($adminId) + $rows, 90000);
} catch (\Throwable $e) {
Log::warning('[ai_mcp] 记录今日行数失败: ' . $e->getMessage());
}
}
private static function rowsKey(int $adminId): string