This commit is contained in:
tangly1024
2021-09-27 09:33:21 +08:00
parent 22ca7f6d63
commit dfc0f645d4
76 changed files with 3650 additions and 2 deletions

21
lib/cache/cache_manager.js vendored Normal file
View File

@@ -0,0 +1,21 @@
import { getCacheFromFile, setCacheToFile } from '@/lib/cache/local_file_cache'
import { getCacheFromMemory, setCacheToMemory } from '@/lib/cache/memory_cache'
import BLOG from '@/blog.config'
export async function getDataFromCache (key) {
let dataFromCache
if (BLOG.isProd) {
dataFromCache = await getCacheFromMemory(key)
} else {
dataFromCache = await getCacheFromFile(key)
}
return dataFromCache
}
export async function setDataToCache (key, data) {
if (BLOG.isProd) {
await setCacheToMemory(key, data)
} else {
await setCacheToFile(key, data)
}
}

36
lib/cache/local_file_cache.js vendored Normal file
View File

@@ -0,0 +1,36 @@
import fs from 'fs'
import BLOG from '@/blog.config'
const path = require('path')
// 文件缓存持续10秒
const cacheInvalidSeconds = 1000000000 * 1000
// 文件名
const jsonFile = path.resolve('./data.json')
export async function getCacheFromFile (key) {
const exist = await fs.existsSync(jsonFile)
if (!exist) return null
const data = await fs.readFileSync(jsonFile)
const json = data ? JSON.parse(data) : {}
// 缓存超过有效期就作废
const cacheValidTime = new Date(parseInt(json[key + '_expire_time']) + cacheInvalidSeconds)
const currentTime = new Date()
if (!cacheValidTime || cacheValidTime < currentTime) {
return null
}
return json[key]
}
/**
* 并发请求写文件异常; Vercel生产环境不支持写文件。
* @param key
* @param data
* @returns {Promise<null>}
*/
export async function setCacheToFile (key, data) {
const exist = await fs.existsSync(jsonFile)
const json = exist ? JSON.parse(await fs.readFileSync(jsonFile)) : {}
json[key] = data
json[key + '_expire_time'] = new Date().getTime()
fs.writeFileSync(jsonFile, JSON.stringify(json))
}

9
lib/cache/memory_cache.js vendored Normal file
View File

@@ -0,0 +1,9 @@
import cache from 'memory-cache'
export async function getCacheFromMemory (key, options) { // url为缓存标识
return cache.get(key)
}
export async function setCacheToMemory (key, data) { // url为缓存标识
await cache.put(key, data, 60 * 1000)
}