feat: 添加分页功能和缓存管理,优化问答记录展示

This commit is contained in:
2026-05-23 00:44:47 +08:00
parent c48d57df14
commit cc7125e681
16 changed files with 172 additions and 243 deletions
-100
View File
@@ -1,100 +0,0 @@
// server/utils/cache.ts - 简单内存缓存,按题目、题型和选项生成缓存键
import { createHash } from "node:crypto";
import { serverEnv } from "~~/server/utils/env";
/**
* 旧 Python 服务使用进程内字典缓存答案
*
* Nuxt 版保持同样的“内存缓存”语义:服务重启后缓存清空,不跨实例共享;
* 这对个人题库服务足够简单,也避免为了缓存引入数据库或 Redis
*/
export class SimpleCache {
/** Map key 是题目、题型和选项计算出的 md5;value 保存写入时间和答案 */
private readonly cache = new Map<
string,
{
timestamp: number;
value: string;
}
>();
constructor(private readonly expirationSeconds: number) {}
/**
* 根据题目、题型和选项生成缓存键
*
* 同一道题如果选项不同,不能复用旧答案,所以三个字段都参与计算
*/
private generateKey(question: string, questionType = "", options = "") {
return createHash("md5")
.update(`${question}|${questionType}|${options}`, "utf8")
.digest("hex");
}
/**
* 读取缓存答案
*
* 命中过期项时会顺手删除,避免长时间运行后堆积无效缓存
*/
get(question: string, questionType = "", options = "") {
const key = this.generateKey(question, questionType, options);
const item = this.cache.get(key);
if (!item) return undefined;
if (Date.now() - item.timestamp < this.expirationSeconds * 1000) {
return item.value;
}
this.cache.delete(key);
return undefined;
}
/** 写入答案缓存,时间戳使用当前进程时间即可 */
set(question: string, answer: string, questionType = "", options = "") {
const key = this.generateKey(question, questionType, options);
this.cache.set(key, {
timestamp: Date.now(),
value: answer
});
}
/** 清空全部缓存,对应 `/api/cache/clear` */
clear() {
this.cache.clear();
}
/**
* 批量移除过期项
*
* 目前在统计缓存大小时调用,避免 stats 返回已经过期的数量
*/
removeExpired() {
const now = Date.now();
let removedCount = 0;
for (const [key, item] of this.cache.entries()) {
if (now - item.timestamp >= this.expirationSeconds * 1000) {
this.cache.delete(key);
removedCount += 1;
}
}
return removedCount;
}
/** 获取当前有效缓存数量 */
size() {
this.removeExpired();
return this.cache.size;
}
}
/**
* 全局答案缓存实例
*
* 如果 `ENABLE_CACHE=false`,导出 undefined,调用处用可选链即可保持逻辑简洁
*/
export const answerCache = serverEnv.enableCache
? new SimpleCache(serverEnv.cacheExpiration)
: undefined;
-4
View File
@@ -73,10 +73,6 @@ export const serverEnv = {
maxTokens: readInteger("MAX_TOKENS", 500),
/** 模型采样温度,越低越稳定 */
temperature: readNumber("TEMPERATURE", 0.7),
/** 是否启用内存缓存 */
enableCache: readBoolean("ENABLE_CACHE", true),
/** 缓存过期时间,单位秒 */
cacheExpiration: readInteger("CACHE_EXPIRATION", 86_400),
/** 预留日志级别配置,目前日志工具只负责安全输出 */
logLevel: readString("LOG_LEVEL", "INFO"),
/** 单行 SSE data 的最大字节数,用于防止异常流无限堆内存 */
+27 -6
View File
@@ -1,5 +1,4 @@
// server/utils/runtimeState.ts - 服务启动时间内存状态 + 问答记录 DB 读写
import { answerCache } from "~~/server/utils/cache";
import { prisma } from "~~/server/utils/db";
import { serverEnv } from "~~/server/utils/env";
@@ -29,6 +28,7 @@ export const addQaRecord = async (record: {
type: string;
options: string;
answer: string;
hash: string;
}) => {
await prisma.qaRecord.create({
data: {
@@ -36,11 +36,34 @@ export const addQaRecord = async (record: {
question: record.question,
type: record.type,
options: record.options || null,
answer: record.answer || null
answer: record.answer || null,
hash: record.hash
}
});
};
/**
* 按用户 + hash 查找 DB 缓存答案
*
* 只返回 cacheClearedAt 之后写入的记录;未存入时间或 hash 为 null 的老记录不会命中
*/
export const lookupCachedAnswer = async (
userId: string,
hash: string,
cacheClearedAt: Date | null
): Promise<string | null> => {
const record = await prisma.qaRecord.findFirst({
where: {
userId,
hash,
...(cacheClearedAt ? { createdAt: { gt: cacheClearedAt } } : {})
},
orderBy: { createdAt: "desc" },
select: { answer: true }
});
return record?.answer ?? null;
};
/**
* 从数据库分页读取指定用户的问答记录,按创建时间倒序
*/
@@ -76,13 +99,11 @@ export const getQaRecords = async (
}));
return { records, total };
};
/** 生成 `/api/stats` 响应,实时计算 uptime 和有效缓存数量 */
/** 生成 `/api/stats` 的基础运行时信息,不包含用户相关数据 */
export const getRuntimeStats = () => {
return {
version: SERVICE_VERSION,
uptime: (Date.now() - startTime) / 1000,
model: serverEnv.openAiModel,
cache_enabled: serverEnv.enableCache,
cache_size: answerCache?.size() ?? 0
model: serverEnv.openAiModel
};
};