Skip to content

Commit

Permalink
Merge pull request #105 from po-lan/main
Browse files Browse the repository at this point in the history
对缓存小优化
  • Loading branch information
MliKiowa authored Jul 5, 2024
2 parents 0a1fc2d + 81134ea commit 70df6e3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
26 changes: 23 additions & 3 deletions src/common/utils/LRUCache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logError, logDebug } from '@/common/utils/log';
import { logError, logDebug } from "@/common/utils/log";

type group_id = number;
type user_id = number;
Expand Down Expand Up @@ -31,7 +31,7 @@ class LRU<T> {
private tail: cacheNode<T> | null = null;
private onFuncs: ((node: cacheNode<T>) => void)[] = [];

constructor(maxAge: number = 2e4, maxSize: number = 5e3) {
constructor(maxAge: number = 6e4, maxSize: number = 5e3) {
this.maxAge = maxAge;
this.maxSize = maxSize;
this.cache = Object.create(null);
Expand All @@ -44,7 +44,7 @@ class LRU<T> {
// 移除LRU节点
private removeLRUNode(node: cacheNode<T>) {
logDebug(
'removeLRUNode',
"removeLRUNode",
node.groupId,
node.userId,
node.value,
Expand Down Expand Up @@ -140,6 +140,26 @@ class LRU<T> {
}
}
}
public get(groupId: group_id): { userId: user_id; value: T }[];
public get(groupId: group_id, userId: user_id): null | { userId: user_id; value: T };
public get(groupId: group_id, userId?: user_id): any {
const groupObject = this.cache[groupId];
if(!groupObject) return userId === undefined ? [] : null;

if (userId === undefined) {
return Object.entries(groupObject).map(([userId, { value }]) => ({
userId: Number(userId),
value,
}));
}

if (groupObject[userId]) {
return { userId, value: groupObject[userId].value };
}

return null;

}
}

export default LRU;
4 changes: 3 additions & 1 deletion src/common/utils/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,10 +408,12 @@ class DBUtil extends DBUtilBase {
logDebug('读取发言时间', groupId);
return new Promise<IRember[]>((resolve, reject) => {
this.db!.all(`SELECT * FROM "${groupId}" `, (err, rows: IRember[]) => {
const cache = this.LURCache.get(groupId).map(e=>({user_id:e.userId, last_sent_time:e.value}));
if (err) {
logError('查询发言时间失败', groupId);
return resolve([]);
return resolve(cache.map(e=>({...e, join_time:0})));
}
Object.assign(rows, cache)
logDebug('查询发言时间成功', groupId, rows);
resolve(rows);
});
Expand Down

0 comments on commit 70df6e3

Please sign in to comment.