缓存优化
This commit is contained in:
tangly1024
2021-12-16 22:01:59 +08:00
parent 54026de51b
commit 6dc1794bdf
6 changed files with 80 additions and 27 deletions

View File

@@ -1,8 +1,8 @@
import BLOG from '@/blog.config'
import { getCacheFromFile, setCacheToFile } from '@/lib/cache/local_file_cache'
import { getCacheFromMemory, setCacheToMemory } from '@/lib/cache/memory_cache'
import BLOG from '@/blog.config'
// 关闭本地缓存
const enableCache = true
const enableCache = true && !BLOG.isProd // 生产环境禁用
const cacheProvider = 'memory' // ['memory','file'] 用内存或data.json做缓存
/**
* 为减少频繁接口请求notion数据将被缓存
@@ -14,21 +14,32 @@ export async function getDataFromCache (key) {
return null
}
let dataFromCache
if (BLOG.isProd) {
dataFromCache = await getCacheFromMemory(key)
} else {
dataFromCache = await getCacheFromFile(key)
switch (cacheProvider) {
case 'memory':
dataFromCache = await getCacheFromMemory(key)
break
case 'file':
dataFromCache = await getCacheFromFile(key)
break
default:
break
}
return dataFromCache
}
export async function setDataToCache (key, data) {
if (!enableCache) {
if (!enableCache || !data) {
return
}
if (BLOG.isProd) {
await setCacheToMemory(key, data)
} else {
await setCacheToFile(key, data)
switch (cacheProvider) {
case 'memory':
await setCacheToMemory(key, data)
break
case 'file':
await setCacheToFile(key, data)
break
default:
break
}
}

View File

@@ -5,5 +5,5 @@ export async function getCacheFromMemory (key, options) { // url为缓存标识
}
export async function setCacheToMemory (key, data) { // url为缓存标识
await cache.put(key, data, 60 * 1000)
await cache.put(key, data, 5 * 60 * 1000)
}

View File

@@ -11,7 +11,8 @@ import { getPostBlocks } from '@/lib/notion/getPostBlocks'
*/
export async function getNotionPageData ({ pageId = BLOG.notionPageId, from }) {
// 尝试从缓存获取
const data = await getDataFromCache('page_record_map_' + pageId)
const cacheKey = 'page_record_map_' + pageId
const data = await getDataFromCache(cacheKey)
if (data) {
console.log('[请求缓存]:', `from:${from}`, `id:${pageId}`)
return data
@@ -19,7 +20,7 @@ export async function getNotionPageData ({ pageId = BLOG.notionPageId, from }) {
const pageRecordMap = await getPageRecordMapByNotionAPI({ pageId, from })
// 存入缓存
if (pageRecordMap) {
await setDataToCache('page_record_map', pageRecordMap)
await setDataToCache(cacheKey, pageRecordMap)
}
return pageRecordMap
}

View File

@@ -3,7 +3,8 @@ import { NotionAPI } from 'notion-client'
import { getDataFromCache, setDataToCache } from '@/lib/cache/cache_manager'
export async function getPostBlocks (id, from) {
let pageBlock = await getDataFromCache('page_block_' + id)
const cacheKey = 'page_block_' + id
let pageBlock = await getDataFromCache(cacheKey)
if (pageBlock) {
console.log('[请求缓存]:', `from:${from}`, `id:${id}`)
return pageBlock
@@ -20,7 +21,7 @@ export async function getPostBlocks (id, from) {
}
if (pageBlock) {
await setDataToCache('page_block_' + id, pageBlock)
await setDataToCache(cacheKey, pageBlock)
}
return pageBlock
}