perf: 优化数据库缓存

This commit is contained in:
linyuchen 2024-03-07 09:00:22 +08:00
parent a66c1a9779
commit ade509f26d

View File

@ -11,6 +11,7 @@ class DBUtil {
private readonly DB_KEY_PREFIX_MSG_SEQ_ID = "msg_seq_id_"; private readonly DB_KEY_PREFIX_MSG_SEQ_ID = "msg_seq_id_";
private db: Level; private db: Level;
private cache: Record<string, RawMessage> = {} // <msg_id_ | msg_short_id_ | msg_seq_id_><id>: RawMessage private cache: Record<string, RawMessage> = {} // <msg_id_ | msg_short_id_ | msg_seq_id_><id>: RawMessage
private currentShortId: number;
/* /*
* *
@ -110,9 +111,9 @@ class DBUtil {
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq; const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq;
msg.msgShortId = shortMsgId; msg.msgShortId = shortMsgId;
try { try {
await this.db.put(shortIdKey, msg.msgId); this.db.put(shortIdKey, msg.msgId).then();
await this.db.put(longIdKey, JSON.stringify(msg)); this.db.put(longIdKey, JSON.stringify(msg)).then();
await this.db.put(seqIdKey, msg.msgId); this.db.put(seqIdKey, msg.msgId).then();
} catch (e) { } catch (e) {
log("addMsg db error", e.stack.toString()); log("addMsg db error", e.stack.toString());
@ -137,16 +138,19 @@ class DBUtil {
} }
private async genMsgShortId(): Promise<number> { private async genMsgShortId(): Promise<number> {
let shortId = -2147483640
const key = "msg_current_short_id"; const key = "msg_current_short_id";
try { if (this.currentShortId === undefined){
let id: string = await this.db.get(key); try {
shortId = parseInt(id); let id: string = await this.db.get(key);
} catch (e) { this.currentShortId = parseInt(id);
} catch (e) {
this.currentShortId = -2147483640
}
} }
shortId++;
await this.db.put(key, shortId.toString()); this.currentShortId++;
return shortId; await this.db.put(key, this.currentShortId.toString());
return this.currentShortId;
} }
} }