增加cache回写入库的机制
This commit is contained in:
parent
feb3ff15fb
commit
e8e40d0d23
@ -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()
|
||||
}
|
||||
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
26
src/schedule/cache.schedule.ts
Normal file
26
src/schedule/cache.schedule.ts
Normal 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()
|
||||
})
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user