【发布时间】:2018-10-01 20:41:58
【问题描述】:
我有一个查询 MySQL 数据库的 Node.js 服务器。它用作返回 JSON 的 api 端点,也是我的 Express 应用程序的后端服务器,它将检索到的列表作为对象返回给视图。
我正在考虑实施flat-cache 以增加响应时间。下面是代码sn-p。
const flatCache = require('flat-cache');
var cache = flatCache.load('productsCache');
//get all products for the given customer id
router.get('/all/:customer_id', flatCacheMiddleware, function(req, res){
var customerId = req.params.customer_id;
//implemented custom handler for querying
queryHandler.queryRecordsWithParam('select * from products where idCustomers = ? order by CreatedDateTime DESC', customerId, function(err, rows){
if(err) {
res.status(500).send(err.message);
return;
}
res.status(200).send(rows);
});
});
//caching middleware
function flatCacheMiddleware(req, res, next) {
var key = '__express__' + req.originalUrl || req.url;
var cacheContent = cache.getKey(key);
if(cacheContent){
res.send(cacheContent);
} else{
res.sendResponse = res.send;
res.send = (body) => {
cache.setKey(key,body);
cache.save();
res.sendResponse(body)
}
next();
}
}
我在本地运行node.js服务器,缓存确实大大减少了响应时间。
但是,我面临两个问题需要您的帮助。
- 在放置 flatCacheMiddleware 中间件之前,我收到了 JSON 格式的响应,现在当我测试时,它会向我发送一个 HTML。我对 JS 严格模式不是很熟悉(打算很快学习),但我相信答案就在 flatCacheMiddleware 函数中。
那么我应该在 flatCacheMiddleware 函数中修改什么以便它向我发送 JSON?
-
我为该客户手动向产品表中添加了一个新行,当我调用端点时,它仍然向我显示旧行。那么什么时候清除缓存呢?
在 web 应用程序中,理想情况下是用户注销时,但如果我将其用作 api 端点(或者即使在 webapp 上,也不能保证用户会以传统方式注销),我该如何确定是否已添加新记录并需要清除缓存。
感谢您的帮助。如果还有其他与node.js缓存相关的建议你们都可以给出,那将是真正有帮助的。
【问题讨论】:
标签: javascript node.js caching