koa-router-cache icon indicating copy to clipboard operation
koa-router-cache copied to clipboard

关于执行流程的以后

Open sumaolin opened this issue 8 years ago • 1 comments

'use strict';

var koa = require('koa');
var cache = require('koa-router-cache');
var MemoryCache = cache.MemoryCache;
var app = koa();
var count = 0;

app.use(cache(app, {
  'GET /' :{
    key: 'cache:index',
    expire: 5 * 1000 ,
    get: MemoryCache.get,
    set: MemoryCache.set,
    passthrough: MemoryCache.passthrough,
    evtName: 'clearIndexCache',
    destroy: MemoryCache.destroy 
  }
}));

app.use(function *() {
  var d = new Date();
  var strDate = (d.getMinutes()+1)+':'+ (d.getSeconds()+1);
  this.body = count++;
  console.log(strDate +' - '+ this.body);  // 这块每次通过浏览器请求的时候都会执行
  if(count === 5){
    count = 0;
    this.app.emit('clearIndexCache');
  }
});

app.listen(3000, function () {
  console.log('listening on 3000');
});

console.log(strDate +' - '+ this.body); // 这块每次通过浏览器请求的时候都会执行 并且每次输出的值也不一样

51:10 - 0
51:11 - 1
51:14 - 2
51:18 - 3
51:18 - 4
51:21 - 0
51:22 - 1
51:26 - 2
51:29 - 3
51:29 - 4

但是浏览器重展示的 数据5s 以内是一样的,有点糊涂了,求解惑

是我理解错了:使用 koa 搭建论坛系统 中的描述!

以上代码的意思是:缓存主页并 5 秒更新一次,第一次请求到来时缓存中间件中没有内容,所以传递到下一个中间件,此时将 this.body 赋值为 0 , count 变为 1,当中间件的 downstream 执行完毕后执行 upstream,此时将 this.body = 0 缓存到内存中,并设置 5 秒的生存期,所以,后续 5 秒之内的所有请求都会因命中缓存而返回 0 。5 秒过后,因为缓存中的内容已经过期被删除,所以下个请求到来时没有命中缓存,此时传递到下一个中间件将 this.body 赋值为 1 , count 变为 2,并更新缓存。直到当 count 变为 5 时,count 被重置为 0,并通过事件触发该路径对应的监听器立即删除缓存中的老数据,这样保证了缓存中的数据都是最新的。

我理解的是:每5s 刷新后,count 递增+1 依次出现,5s 没刷新这个数不会变。

sumaolin avatar May 11 '16 09:05 sumaolin

favicon.ico 的原因吧。console.log(this.path)看下

nswbmw avatar May 11 '16 09:05 nswbmw