diff --git a/lib/cache/cache_manager.js b/lib/cache/cache_manager.js index 470a0f1a..f0c412ab 100644 --- a/lib/cache/cache_manager.js +++ b/lib/cache/cache_manager.js @@ -3,13 +3,61 @@ import FileCache from './local_file_cache' import MemoryCache from './memory_cache' import RedisCache from './redis_cache' +// 配置是否开启Vercel环境中的缓存,因为Vercel中现有两种缓存方式在无服务环境下基本都是无意义的,纯粹的浪费资源 +const enableCacheInVercel = + process.env.npm_lifecycle_event === 'build' || + process.env.npm_lifecycle_event === 'export' || + !BLOG['isProd'] + +/** + * 尝试从缓存中获取数据,如果没有则尝试获取数据并写入缓存,最终返回所需数据 + * @param key + * @param getDataFunction + * @param getDataArgs + * @returns {Promise<*|null>} + */ +export async function getOrSetDataWithCache( + key, + getDataFunction, + ...getDataArgs +) { + return getOrSetDataWithCustomCache(key, null, getDataFunction, ...getDataArgs) +} + +/** + * 尝试从缓存中获取数据,如果没有则尝试获取数据并自定义写入缓存,最终返回所需数据 + * @param key + * @param customCacheTime + * @param getDataFunction + * @param getDataArgs + * @returns {Promise<*|null>} + */ +export async function getOrSetDataWithCustomCache( + key, + customCacheTime, + getDataFunction, + ...getDataArgs +) { + const dataFromCache = await getDataFromCache(key) + if (dataFromCache) { + console.log('[缓存-->>API]:', key) + return dataFromCache + } + const data = await getDataFunction(...getDataArgs) + if (data) { + console.log('[API-->>缓存]:', key) + await setDataToCache(key, data, customCacheTime) + } + return data || null +} + /** * 为减少频繁接口请求,notion数据将被缓存 * @param {*} key * @returns */ export async function getDataFromCache(key, force) { - if (enableCacheInVercel || BLOG.ENABLE_CACHE || force) { + if (BLOG.ENABLE_CACHE || force) { const dataFromCache = await getApi().getCache(key) if (!dataFromCache || JSON.stringify(dataFromCache) === '[]') { return null @@ -21,6 +69,13 @@ export async function getDataFromCache(key, force) { } } +/** + * 写入缓存 + * @param {*} key + * @param {*} data + * @param {*} customCacheTime + * @returns + */ export async function setDataToCache(key, data, customCacheTime) { if (!enableCacheInVercel || !data) { return @@ -40,7 +95,7 @@ export async function delCacheData(key) { * 缓存实现类 * @returns */ -function getApi() { +export function getApi() { if (BLOG.REDIS_URL) { return RedisCache } else if (process.env.ENABLE_FILE_CACHE) { diff --git a/lib/cache/redis_cache.js b/lib/cache/redis_cache.js index 2556a815..b35f472a 100644 --- a/lib/cache/redis_cache.js +++ b/lib/cache/redis_cache.js @@ -1,8 +1,9 @@ -import Redis from 'ioredis' import BLOG from '@/blog.config' import { siteConfig } from '@/lib/config' +import Redis from 'ioredis' + +export const redisClient = BLOG.REDIS_URL ? new Redis(BLOG.REDIS_URL) : {} -export const redisClient = new Redis(BLOG.REDIS_URL) const cacheTime = Math.trunc( siteConfig('NEXT_REVALIDATE_SECOND', BLOG.NEXT_REVALIDATE_SECOND) * 1.5 )