express.js做后端cache

有时候我在想,我为什么这么喜欢用node.js。其实不是它自身多好,而是因为它吸引了无数talent为npm贡献智慧,而我们只要使用就好了

为了降低对存储端的读取压力,有时候需要在express里加缓存,用来缓存request并直接response

推荐使用apicache

你可以缓存所有请求,也可以按router来缓存,我们来使用后者,按需cache

  1. npm安装apicache
  2. router cache
    var cache = require('apicache').middleware;
    ...
    
    //以中间件的形式使用,我们缓存6分钟,此期间直接相应
    router.get('/:name', cache('6 minutes'), function (req, res, next) {
    ...
    }
    
    module.exports = router;

     

  3. 默认对request做key,也支持自定义的key
    //例如对get/post + session.id做key,其他参数不管
    apicache.options({
      appendKey: (req, res) => req.method + res.session.id
    })

     

正如文档所言,everythis is automagic!

posted @ 2017-09-28 17:51  Els0n  阅读(321)  评论(0编辑  收藏  举报