簡體   English   中英

Node.js 平面緩存,何時清除緩存

[英]Node.js flat-cache, when to clear caches

我有一個查詢 MySQL 數據庫的 Node.js 服務器。 它作為一個 api 端點,它返回 JSON,也是我的 Express 應用程序的后端服務器,它將檢索到的列表作為對象返回給視圖。

我正在考慮實施平面緩存以增加響應時間。 下面是代碼片段。

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 緩存相關的建議,那將非常有幫助。

廣告 1. 我修復了將解析內容添加到 JSON 的問題。

換行:

res.send(cacheContent);

進入:

res.send(JSON.parse(cacheContent));

廣告 2. 我創建了緩存“蠻力”失效方法。 調用 clear 方法將清除緩存文件和存儲在內存中的數據。 您必須在數據庫更改后調用它。 您也可以嘗試使用cache.removeKey('key');刪除指定的鍵cache.removeKey('key');

功能清除(請求,資源,下一個){

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)將“防止刪除未訪問的鍵”(如https://www.npmjs.com/package/flat-cache中的評論中所述)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM