我的后端Nodejs必须对外部服务进行一些API GET请求调用,以检索数据并用作网页。这些API调用正在缓存中。
由于我使用的是Heroku,因此每次应用进入休眠状态时都会删除此数据。是否有任何持久性缓存库?目前,我正在使用lru-cache
和axios-extensions
。
const axios = require('axios');
const { cacheAdapterEnhancer } = require('axios-extensions');
const LRUCache = require("lru-cache")
const options = {
defaultCache: new LRUCache({ maxAge: 60 * 60 * 1000, max: 100 })
}
const http = axios.create({
headers: { 'Cache-Control': 'no-cache' },
timeout: 60000,
adapter: cacheAdapterEnhancer(axios.defaults.adapter)
}
)
getData: async () => {
try {
const response = await http.get(url, config)
const data = response.data
return data
} catch (error) {
console.log(error)
}
}
答案 0 :(得分:0)
正如@giankotarola在评论中建议的那样,我需要使用缓存数据库来解决该问题。最终,我设法使用Redis使其工作!我的最终代码:
const axios = require('axios')
const redis = require('redis')
// create and connect redis client to local instance.
const client = redis.createClient()
// Print redis errors to the console
client.on('error', (err) => {
console.log("Error " + err)
});
const http = axios.create({
headers: { 'Cache-Control': 'no-cache' },
timeout: 60000
}
)
let config = {
headers: {
Authorization: `Bearer ${API_KEY}`,
}
}
let url = 'https://example.com'
module.exports={
getData: async () => {
try {
// Try to get response from Redis store
const response = await client.get(url)
return responseJSON = JSON.parse(response)
} catch (err) {
try {
const response = await http.get(url, config)
const data = response.data
// Save response in Redis store
client.setex(url, 60 * 60 * 1000, JSON.stringify(data));
return data
} catch (error) {
console.log(error)
}
}
}
}