koa-router-cache 可以用来缓存路由数据信息,可以使用内存或是redis进行数据缓存,对于内容页面来说,可以将页面缓存在内存中,以减少不必要的数据库请求。
koa-router-cache 使用的还是koa的插件生成方法,所以需要使用koa-convert转换成支持kao2的函数。
下面是使用内存级别的缓存,服务重启之后,缓存数据失效,可以使用redis缓存来进行持久化,redis配置可以直接参考koa-router-cache的文档进行配置。
// 配置使用路由请求缓存 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 } })));
因为这里的key,使用的正则,也就是说key是变化的,但对于destroy来说,并不知道你要销毁哪一个key,但是我们在后台进行编辑文章或是其他内容的时候,会知道需要处理哪一个缓存路由路径,可以在调用ctx.app.emit的时候传入参数
ctx.app.emit('clearIndexCache', `/post/${postname}.html`)
这个时候,就需要改写一个destroy的回调方法了,虽然这种方法可能并不是最完美的,但可以删除指定的路径缓存,这样其他内容就可以保持不变。
destroy: function (key,path) { MemoryCache.destroy(path) }