增加cache回写入库的机制

This commit is contained in:
CounterFire2023 2024-01-11 16:21:33 +08:00
parent feb3ff15fb
commit e8e40d0d23
3 changed files with 40 additions and 2 deletions

View File

@ -10,6 +10,7 @@ import logger from 'logger/logger'
import { RedisClient } from 'redis/RedisClient'
import NonceRecordSchedule from 'schedule/noncerecord.schedule'
import { SyncLocker } from 'common/SyncLocker'
import CacheSchedule from 'schedule/cache.schedule'
const zReqParserPlugin = require('plugins/zReqParser')
@ -106,6 +107,7 @@ export class ApiServer {
logger.log('REDIS Connected')
}
private initSchedules() {
new CacheSchedule().scheduleAll()
new NonceRecordSchedule().scheduleAll()
}

View File

@ -2,9 +2,11 @@ import { singleton } from "decorators/singleton";
import { LotteryStats } from "models/LotteryStats";
import { formatDate } from "utils/date.util";
const EXPIRE_TIME = 1000 * 60 * 60;
@singleton
export class LotteryCache {
map: Map<string, typeof LotteryStats> = new Map();
lastUsed: Map<string, number> = new Map();
public async getData(user: string, activity: string) {
const dateTag = formatDate(new Date());
@ -12,11 +14,19 @@ export class LotteryCache {
const record = await LotteryStats.insertOrUpdate({user, activity, dateTag}, {})
this.map.set(user+dateTag, record);
}
this.lastUsed.set(user+dateTag, Date.now());
return this.map.get(user+dateTag);
}
public async flush() {
for (let record of this.map.values()) {
await record.save();
for (let [key, record] of this.map.entries()) {
// record.modifiedPaths()
if (record.isModified()) {
await record.save();
}
if (Date.now() - this.lastUsed.get(key) > EXPIRE_TIME) {
this.map.delete(key);
this.lastUsed.delete(key);
}
}
}
}

View File

@ -0,0 +1,26 @@
import { LotteryCache } from 'common/LotteryCache';
import { singleton } from 'decorators/singleton'
import logger from 'logger/logger';
import {NonceRecord} from 'models/NonceRecord'
import * as schedule from 'node-schedule'
/**
*
*/
@singleton
export default class CacheSchedule {
async updateCache() {
try {
new LotteryCache().flush();
} catch (err) {
logger.warn(err)
}
}
scheduleAll() {
schedule.scheduleJob('*/10 * * * * *', async () => {
await this.updateCache()
})
}
}