ts-api-core
Version:
Nodejs api framework core
62 lines • 2.01 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalCache = void 0;
/**
* 本地内存高速数据缓存
*/
class LocalCache {
/**
* 添加缓存
* @param key 缓存key
* @param data 数据
* @param timeOut 数据超时时间(ms, <= 0 永不超时,超时自动清理)
* @param ver 数据版本号
*/
static set(key, data, timeOut = 0, ver = 0) {
this._cacheData.set(key, {
time: new Date().getTime(),
ver,
data,
timeOut
});
}
/** 获取缓存,只有数据版本号大于等于指定版本号才返回 */
static get(key, ver = 0) {
const v = this._cacheData.get(key);
return v && v.ver >= ver && (v.timeOut <= 0 || new Date().getTime() - v.time <= v.timeOut) ? v.data : undefined;
}
/** 检测缓存是否存在和有效 */
static has(key, ver = 0) {
const v = this._cacheData.get(key);
return v ? v.ver >= ver && (v.timeOut <= 0 || new Date().getTime() - v.time <= v.timeOut) : false;
}
/** 删除指定缓存 */
static delete(key) {
return this._cacheData.delete(key);
}
/** 清空缓存 */
static clear() {
this._cacheData.clear();
}
/** 真实的缓存数量(包含还未清理的已超时数据) */
static get size() {
return this._cacheData.size;
}
}
exports.LocalCache = LocalCache;
LocalCache._cacheData = new Map();
/** 清理缓存 */
LocalCache._cacheClearTimer = setInterval(() => {
if (LocalCache._cacheData.size === 0) {
return;
}
const time = new Date().getTime();
const keys = [];
LocalCache._cacheData.forEach((v, key) => {
if (v.timeOut > 0 && time - v.time > v.timeOut) {
keys.push(key);
}
});
keys.forEach(v => LocalCache._cacheData.delete(v));
}, 60000);
//# sourceMappingURL=local.cache.js.map