mirror of
https://github.com/DIYgod/RSSHub.git
synced 2025-12-11 15:47:48 +08:00
Implement persistent cache
This commit is contained in:
@@ -14,19 +14,28 @@ module.exports = function(options = {}) {
|
||||
ignoreQuery = false,
|
||||
} = options;
|
||||
|
||||
const memoryCache = new lru({
|
||||
const temporaryCache = new lru({
|
||||
maxAge: expire * 1000,
|
||||
max: maxLength,
|
||||
});
|
||||
|
||||
const persistentCache = new lru({
|
||||
maxAge: expire * 1000,
|
||||
max: maxLength,
|
||||
updateAgeOnGet: true,
|
||||
});
|
||||
|
||||
options.app.context.cache = {
|
||||
get: (key) => {
|
||||
get: (key, persistent) => {
|
||||
if (key) {
|
||||
return memoryCache.get(key);
|
||||
if (persistent) {
|
||||
return persistentCache.get(key);
|
||||
} else {
|
||||
return temporaryCache.get(key);
|
||||
}
|
||||
}
|
||||
},
|
||||
set: (key, value, maxAge) => {
|
||||
set: (key, value, maxAge, persistent) => {
|
||||
if (!value || value === 'undefined') {
|
||||
value = '';
|
||||
}
|
||||
@@ -34,7 +43,11 @@ module.exports = function(options = {}) {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
if (key) {
|
||||
memoryCache.set(key, value, maxAge * 1000);
|
||||
if (persistent) {
|
||||
return persistentCache.set(key, value, maxAge * 1000);
|
||||
} else {
|
||||
return temporaryCache.set(key, value, maxAge * 1000);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -76,13 +89,14 @@ module.exports = function(options = {}) {
|
||||
* getCache
|
||||
*/
|
||||
async function getCache(ctx, key, tkey) {
|
||||
const value = memoryCache.get(key);
|
||||
let type;
|
||||
const value = temporaryCache.get(key);
|
||||
|
||||
let ok = false;
|
||||
|
||||
if (value) {
|
||||
ctx.response.status = 200;
|
||||
type = memoryCache.get(tkey) || 'text/html';
|
||||
type = temporaryCache.get(tkey) || 'text/html';
|
||||
// can happen if user specified return_buffers: true in redis options
|
||||
if (Buffer.isBuffer(type)) {
|
||||
type = type.toString();
|
||||
@@ -115,7 +129,7 @@ module.exports = function(options = {}) {
|
||||
if (Buffer.byteLength(body) > maxLength) {
|
||||
return;
|
||||
}
|
||||
memoryCache.set(key, body);
|
||||
temporaryCache.set(key, body);
|
||||
|
||||
await cacheType(ctx, tkey);
|
||||
}
|
||||
@@ -126,7 +140,7 @@ module.exports = function(options = {}) {
|
||||
async function cacheType(ctx, tkey) {
|
||||
const type = ctx.response.headers['content-type'];
|
||||
if (type) {
|
||||
memoryCache.set(tkey, type);
|
||||
temporaryCache.set(tkey, type);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user