更新缓存机制
This commit is contained in:
parent
82bff3babf
commit
db2c953ae6
26
index.js
26
index.js
@ -29,6 +29,20 @@ if (!fs.existsSync(cacheDir)) {
|
||||
fs.mkdirSync(cacheDir);
|
||||
}
|
||||
|
||||
|
||||
// 定时清理过期缓存数据并更新请求
|
||||
setInterval(async () => {
|
||||
const currentTime = Date.now();
|
||||
for (const key in pathIndex) {
|
||||
const { timestamp } = pathIndex[key];
|
||||
// 24小时
|
||||
if (currentTime - timestamp > 24 * 60 * 60 * 1000) {
|
||||
delete pathIndex[key];
|
||||
}
|
||||
}
|
||||
}, 1 * 60 * 60 * 1000); // 每隔 1 小时执行一次
|
||||
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (req.url === '/favicon.ico') {
|
||||
res.writeHead(204);
|
||||
@ -53,8 +67,8 @@ const server = http.createServer(async (req, res) => {
|
||||
let tempCacheContentFile = '';
|
||||
|
||||
if (pathIndex[uniqidhex]) {
|
||||
cacheMetaFile = pathModule.join(cacheDir, `${pathIndex[uniqidhex]}.meta`);
|
||||
cacheContentFile = pathModule.join(cacheDir, `${pathIndex[uniqidhex]}.content`);
|
||||
cacheMetaFile = pathModule.join(cacheDir, `${pathIndex[uniqidhex].uniqid}.meta`);
|
||||
cacheContentFile = pathModule.join(cacheDir, `${pathIndex[uniqidhex].uniqid}.content`);
|
||||
}
|
||||
|
||||
if (pathIndex[uniqidhex] && isCacheValid(cacheMetaFile, cacheContentFile)) {
|
||||
@ -66,16 +80,18 @@ const server = http.createServer(async (req, res) => {
|
||||
const { url: realUrl, cloudtype, expiration, path, headers, uniqid } = apiData.data;
|
||||
const data = { realUrl, cloudtype, expiration: expiration * 1000, path, headers, uniqid };
|
||||
|
||||
pathIndex[uniqidhex] = data.uniqid;
|
||||
// 修改 pathIndex 记录时,添加时间戳
|
||||
pathIndex[uniqidhex] = { uniqid: data.uniqid, timestamp: Date.now() };
|
||||
|
||||
|
||||
cacheMetaFile = pathModule.join(cacheDir, `${data.uniqid}.meta`);
|
||||
cacheContentFile = pathModule.join(cacheDir, `${data.uniqid}.content`);
|
||||
tempCacheContentFile = pathModule.join(cacheDir, `${data.uniqid}_${crypto.randomBytes(16).toString('hex')}.temp`);
|
||||
|
||||
if (expiration > 0) {
|
||||
// 重新写入 meta 缓存
|
||||
fs.writeFileSync(cacheMetaFile, JSON.stringify(data));
|
||||
}
|
||||
|
||||
// 如果内容缓存存在, 则直接调用
|
||||
if (fs.existsSync(cacheContentFile)) {
|
||||
serveFromCache(cacheMetaFile, cacheContentFile, res);
|
||||
return;
|
||||
|
Loading…
x
Reference in New Issue
Block a user