【问题标题】:Node.js flat-cache, when to clear cachesNode.js 平面缓存,何时清除缓存
【发布时间】: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服务器,缓存确实大大减少了响应时间。

但是,我面临两个问题需要您的帮助。

  1. 在放置 flatCacheMiddleware 中间件之前,我收到了 JSON 格式的响应,现在当我测试时,它会向我发送一个 HTML。我对 JS 严格模式不是很熟悉(打算很快学习),但我相信答案就在 flatCacheMiddleware 函数中。

那么我应该在 flatCacheMiddleware 函数中修改什么以便它向我发送 JSON?

  1. 我为该客户手动向产品表中添加了一个新行,当我调用端点时,它仍然向我显示旧行。那么什么时候清除缓存呢?

    在 web 应用程序中,理想情况下是用户注销时,但如果我将其用作 api 端点(或者即使在 webapp 上,也不能保证用户会以传统方式注销),我该如何确定是否已添加新记录并需要清除缓存。

感谢您的帮助。如果还有其他与node.js缓存相关的建议你们都可以给出,那将是真正有帮助的。

【问题讨论】:

    标签: javascript node.js caching


    【解决方案1】:
    1. 我通过将内容解析为 JSON 格式找到了该问题的解决方案。

    换行:

    res.send(cacheContent);
    

    收件人:

    res.send(JSON.parse(cacheContent));
    
    1. 我创建了缓存“蛮力”失效方法。调用 clear 方法将清除缓存文件和存储在内存中的数据。您必须在 db 更改后调用它。您也可以尝试使用cache.removeKey('key'); 删除指定的密钥。
    function clear(req, res, next) {
        try {
            cache.destroy()
        } catch (err) {
            logger.error(`cache invalidation error ${JSON.stringify(err)}`);
            res.status(500).json({
                'message' : 'cache invalidation error',
                'error' : JSON.stringify(err)
            });
        } finally {
            res.status(200).json({'message' : 'cache invalidated'})
        }
        
    }
    
    1. 注意,调用cache.save() 函数将删除其他缓存的API 函数。将其更改为cache.save(true) 将“防止删除未访问的密钥”(如the flat-cache documentation 中的评论中所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      • 2012-11-12
      • 2011-05-10
      • 1970-01-01
      相关资源
      最近更新 更多