web开发中缓存优化

浏览器缓存

  • 强缓存

Expires (Expires:Thu, 30 Dec 2027 11:02:20 GMT)
Cache-Control (Cache-Control:max-age=315360000)

  • 协商缓存

If-Modified-Since / Last-Modified (Last-Modified:Wed, 22 Jun 2011 06:40:43 GMT)
If-None-Match / Etag (Etag:"2c1-4a6473f6030c0")

web开发中缓存优化_第1张图片
缓存实现流程

//配置缓存参数
cache: {
    maxAge: 600,
    expires: true,
    cacheControl: true,
    lastModified: true,
    etag: true
}
//定义缓存函数
const {cache} = require('../config/defaultConfig')

function refreshRes(stats,res) {
    if(cache.expires){
        res.setHeader('Expires',(new Date(Date.now() + cache.maxAge*1000)).toUTCString())
    }
    if(cache.cacheControl){
        res.setHeader('Cache-Control',`public,max-age=${cache.maxAge}`)

    }
    if(cache.lastModified){
        res.setHeader('Last-Modified',stats.mtime.toUTCString())
    }
    if(cache.etag){
        res.setHeader('ETag',`${stats.size}-${stats.mtime}`)
    }

}

module.exports = function (stats,req,res) {

    refreshRes(stats,res)

    const lastModified = req.headers['if-modified-since']
    const etag = req.headers['if-none-match']

    if(!lastModified && !etag){
        return false
    }
    const aaa = res.getHeaders()['last-modified']
    if(lastModified && lastModified !== res.getHeaders()['last-modified']){
        return false
    }

    if(etag && etag !== res.getHeaders()['etag']){
        return false
    }

    return true

}
//判断是否使用缓存
const isUseCache = require('../handle/cache')
if(isUseCache(stats,req,res)){
    res.statusCode = 304
    res.end()
    return
}

  • 彻底弄懂HTTP缓存机制及原理
  • 缓存在高并发场景下的常见问题
  • HTTP缓存是如何实现

你可能感兴趣的:(web开发中缓存优化)