router\web\index.js:
const Router = require('koa-router');
let router = new Router();
// 静态化
// 寻找缓存
router.get('/', async (ctx, next)=>{
let key = 'page:';
let maxage = 1 * 86400 * 1000;
let data = await ctx.redis.getAsync(key);
if(data) {
console.log('from cache')
ctx.body = data;
}else{
console.log('from render')
await next();
await ctx.redis.psetexAsync(key, maxage, ctx.body);
}
})
// 生成
router.get('/', async ctx=>{
ctx.body = '首页';
});
module.exports = router.routes();
独立成工具:
index.js:
const Router = require('koa-router');
const static = require('../../libs/contentStatic');
let router = new Router();
// 静态化
// 寻找缓存
router.get('/',
static('page:'),
// 生成
async ctx=>{
ctx.body = '首页';
}
)
router.get('/', );
module.exports = router.routes();
contentStatic.js:
const assert = require('assert'); // 断言key
module.exports = function(key, maxage = 1 * 86400 * 1000) {
assert(key, 'key is require');
return async (ctx, next)=>{
let data = await ctx.redis.getAsync(key);
if(data) {
console.log('from cache')
ctx.body = data;
}else{
console.log('from render')
await next();
await ctx.redis.psetexAsync(key, maxage, ctx.body);
}
};
}