这里是关于应用程序结构的一般查询。基本上,我有一个 SPA,旨在显示来自第 3 方 API 的赔率。
为了减少该 API 的工作量,我想构建一个 Node/express 中间件,以便查询首先检查 memcache/redis 缓存,如果已缓存,并且值相同,则返回数据,如果没有缓存,则返回数据点击 API 并返回响应,同时添加到缓存以供 future 查询,时间限制为 X。(不确定我是否需要像 mongodb 这样的实际数据库来使用缓存)
这里我想要实现的关键部分是缓存,因为我想避免 API 在数据相同时必须响应,从而避免缓存。
我想我的问题是上述场景是否有意义,还是我在开始之前就将其复杂化了?
对任何错误表示歉意,后端和缓存对我来说非常陌生。
提前致谢
最佳答案
这个想法是首先检查数据是否在缓存中,如果没有,则从 API 获取数据并写入缓存。
这是使用 redis
和 request
实现的示例
function getThirdParty(req,res){
//unique identifier for the cache
const redisKey = req.body.key
//check the result is in cache
client.getAsync(redisKey).then(function(result) {
if(result){
res.json({
result:result,
cache:true
})
}else{
//not in cache made the api request
request('http://www.thirdpartyapi.com', function (error, response, body) {
//set the api result in cache
client.set(redisKey,body);
res.json({
result:body,
cache:false
})
});
}
});
}
关于node.js - Node/Express 应用程序用于查询第 3 方 API 并将响应存储在 memcache/redis 中 30 分钟以供将来查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53496689/