koa-router-cache 可以用来缓存路由数据信息,可以使用内存或是redis进行数据缓存,对于内容页面来说,可以将页面缓存在内存中,以减少不必要的数据库请求。
koa-router-cache 使用的还是koa的插件生成方法,所以需要使用koa-convert转换成支持kao2的函数。
下面是使用内存级别的缓存,服务重启之后,缓存数据失效,可以使用redis缓存来进行持久化,redis配置可以直接参考koa-router-cache的文档进行配置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // 配置使用路由请求缓存 const convert = require('koa-convert') // 可以将不支持koa2的函数进行转换 const cache = require('koa-router-cache'); const MemoryCache = cache.MemoryCache; app.use(convert(cache(app, { 'GET /post/:id(\\d+).html': { key: function *(){ // key可以是字符串,也可以是generator函数,可以动态生成key return this.path }, expire: 1000*60*60*24, get: function *(key) { logger.info('[已缓存缓存]',this.path) let cm = yield MemoryCache.get(key) return cm }, set: MemoryCache.set, passthrough: MemoryCache.passthrough, evtName: 'clearIndexCache', destroy: MemoryCache.destroy } }))); |