Merge pull request #3114 from qixing-jk/perf-vercel-data-cache

Perf vercel data cache
This commit is contained in:
tangly1024
2025-01-05 19:21:58 +08:00
committed by GitHub

View File

@@ -2,6 +2,12 @@ import BLOG from '@/blog.config'
import FileCache from './local_file_cache'
import MemoryCache from './memory_cache'
// 配置是否开启Vercel环境中的缓存因为Vercel中现有两种缓存方式在无服务环境下基本都是无意义的纯粹的浪费资源
const enableCacheInVercel =
process.env.npm_lifecycle_event === 'build' ||
process.env.npm_lifecycle_event === 'export' ||
!BLOG['isProd']
/**
* 尝试从缓存中获取数据,如果没有则尝试获取数据并写入缓存,最终返回所需数据
* @param key
@@ -42,8 +48,8 @@ export async function getOrSetDataWithCustomCache(key, customCacheTime, getDataF
* @returns
*/
export async function getDataFromCache(key, force) {
if (BLOG.ENABLE_CACHE || force) {
const dataFromCache = await getApi().getCache(key)
if (enableCacheInVercel || BLOG.ENABLE_CACHE || force) {
const dataFromCache = await cacheApi.getCache(key)
if (!dataFromCache || JSON.stringify(dataFromCache) === '[]') {
return null
}
@@ -55,28 +61,19 @@ export async function getDataFromCache(key, force) {
}
export async function setDataToCache(key, data, customCacheTime) {
if (!data) {
if (!enableCacheInVercel || !data) {
return
}
// console.trace('[API-->>缓存写入]:', key)
await getApi().setCache(key, data, customCacheTime)
await cacheApi.setCache(key, data, customCacheTime)
}
export async function delCacheData(key) {
if (!JSON.parse(BLOG.ENABLE_CACHE)) {
return
}
await getApi().delCache(key)
await cacheApi.delCache(key)
}
/**
* 缓存实现类
* @returns
*/
function getApi() {
if (process.env.ENABLE_FILE_CACHE) {
return FileCache
} else {
return MemoryCache
}
}
// 缓存实现类
const cacheApi = process.env.ENABLE_FILE_CACHE ? FileCache : MemoryCache