Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于执行流程的以后 #3

Open
sumaolin opened this issue May 11, 2016 · 1 comment
Open

关于执行流程的以后 #3

sumaolin opened this issue May 11, 2016 · 1 comment

Comments

@sumaolin
Copy link

'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 没刷新这个数不会变。

@nswbmw
Copy link
Owner

nswbmw commented May 11, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants