feat(core): caching enhancements (#9227)

* fix(core): redis cache ignore `maxAge` when refreshing

memory cache do not have such a problem

Signed-off-by: Rongrong <15956627+Rongronggg9@users.noreply.github.com>

* feat(core): make `cache.tryGet()` refreshing selectable

Signed-off-by: Rongrong <15956627+Rongronggg9@users.noreply.github.com>

* docs: `ctx.cache.tryGet()` update

Signed-off-by: Rongrong <15956627+Rongronggg9@users.noreply.github.com>
This commit is contained in:
Rongrong
2022-03-19 02:13:15 +08:00
committed by GitHub
parent 933080a1f5
commit 41910802f2
4 changed files with 21 additions and 6 deletions
+2 -2
View File
@@ -55,8 +55,8 @@ module.exports = function (app) {
const { get, set, status } = cacheModule;
app.context.cache = {
...cacheModule,
tryGet: async (key, getValueFunc, maxAge = config.cache.contentExpire) => {
let v = await get(key);
tryGet: async (key, getValueFunc, maxAge = config.cache.contentExpire, refresh = true) => {
let v = await get(key, refresh);
if (!v) {
v = await getValueFunc();
set(key, v, maxAge);
+17 -2
View File
@@ -18,12 +18,26 @@ redisClient.on('connect', () => {
logger.info('Redis connected.');
});
const getCacheTtlKey = (key) => {
if (key.startsWith('cacheTtl:')) {
throw Error('"cacheTtl:" prefix is reserved for the internal usage, please change your cache key'); // blocking any attempt to get/set the cacheTtl
}
return `cacheTtl:${key}`;
};
module.exports = {
get: async (key, refresh = true) => {
if (key && status.available) {
let value = await redisClient.get(key);
const cacheTtlKey = getCacheTtlKey(key);
let [value, cacheTtl] = await redisClient.mget(key, cacheTtlKey);
if (value && refresh) {
redisClient.expire(key, config.cache.contentExpire);
if (!cacheTtl) {
cacheTtl = config.cache.contentExpire;
redisClient.set(cacheTtlKey, cacheTtl, 'EX', cacheTtl);
} else {
redisClient.expire(cacheTtlKey, cacheTtl);
}
redisClient.expire(key, cacheTtl);
value = value + '';
}
return value;
@@ -40,6 +54,7 @@ module.exports = {
value = JSON.stringify(value);
}
if (key) {
redisClient.set(getCacheTtlKey(key), maxAge, 'EX', maxAge);
return redisClient.set(key, value, 'EX', maxAge); // setMode: https://redis.io/commands/set
}
},