Skip to content

Instantly share code, notes, and snippets.

@z2015
Last active July 13, 2016 05:55
Show Gist options
  • Save z2015/5aac93f6fd74b167156f1d83e37fef3f to your computer and use it in GitHub Desktop.
Save z2015/5aac93f6fd74b167156f1d83e37fef3f to your computer and use it in GitHub Desktop.

Revisions

  1. z2015 revised this gist Jul 13, 2016. 1 changed file with 4 additions and 2 deletions.
    6 changes: 4 additions & 2 deletions cache.md
    Original file line number Diff line number Diff line change
    @@ -38,7 +38,7 @@ app.use(function* index(next){
    'Last-Modified': this.indexfile.ctime.toUTCString()
    });
    this.set({
    'Cache-Control':'no-cache'
    'Cache-Control':'30'
    });
    if (this.fresh){
    this.status = 304;
    @@ -52,4 +52,6 @@ app.use(function* index(next){
    if (!module.parent) {
    app.listen(3000);
    }
    ```
    ```

    上述情况是在30秒时间内可以直接使用缓存,超过30秒之后需要请求服务器,如果缓存最新,直接返回304,否则返回最新内容。
  2. z2015 created this gist Jul 13, 2016.
    55 changes: 55 additions & 0 deletions cache.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    #Cache-Control适用场合
    该参数用于缓存控制,在设置了该值后,浏览器会在超过该时间的情况下强行请求一次服务器,否则会一直使用上一次访问时的数据。
    例如max-age=60,这里就告诉了浏览器在60秒内可以使用缓存,超过后需要重新向服务器发送请求。
    这里要注意的事文件的访问方式局限于该文件是被其它文件所调用,或者是在新窗口访问该文件,如果在访问单个文件时使用了浏览器上的刷新按钮,那么就会浏览器就会强行触发一次发向服务器的请求。
    这也就为什么很多人发现Cache-Control设置失效的原因。

    #ETag的作用
    该值一般是由服务器端生成的一段随机代码,用于指示当前访问文件的特殊值(文件的任何改变都会导致其改变)。一般用于校验当前文件是否是最新的文件。

    #Cache-Control结合ETag的用法
    在后台获取当前文件的ETag值,并设置,当Cache-Control缓存过期时,后端先判断请求头的'If-None-Match'是否和当前Etag相等,如果相等的话,那么直接返回304http状态,指示浏览器可以继续使用当前的缓存内容。这样可以节省很多的网络请求同时还能提高访问速度。
    下面是一个示范

    ```js
    var path = require('path');
    var fs = require('fs');
    var thunkify = require('thunkify');
    var koa = require('koa');
    var render = require('koa-swig');
    var app = koa();
    var staticCache = require('koa-static-cache');
    var stat = thunkify(fs.stat);
    var etag = require('etag')

    app.context.render = render({
    root: path.join(__dirname, 'views'),
    autoescape: true,
    cache: false,
    ext: 'html'
    });

    app.use(function* index(next){
    app.context.indexfile = yield stat(path.join(__dirname,'views/index.html'));
    console.log('hit');
    this.status = 200;
    this.set({
    "ETag": etag(this.indexfile),
    'Last-Modified': this.indexfile.ctime.toUTCString()
    });
    this.set({
    'Cache-Control':'no-cache'
    });
    if (this.fresh){
    this.status = 304;
    this.response.remove('Content-Type');
    this.response.remove('Content-Length');
    return;
    }
    yield this.render('index');
    });

    if (!module.parent) {
    app.listen(3000);
    }
    ```