node强缓存和协商缓存怎么实现

发布时间:2022-09-21 17:09:21 作者:iii
来源:亿速云 阅读:213

Node强缓存和协商缓存怎么实现

在Web开发中,缓存是提高应用性能的重要手段之一。通过缓存,可以减少服务器负载、加快页面加载速度,并提升用户体验。Node.js作为后端开发的热门选择,提供了多种方式来实现缓存机制。本文将详细介绍如何在Node.js中实现强缓存和协商缓存。

1. 缓存的基本概念

缓存可以分为两种主要类型:强缓存协商缓存

2. 强缓存的实现

强缓存主要通过设置响应头中的Cache-ControlExpires字段来实现。

2.1 使用Cache-Control

Cache-Control是HTTP/1.1中引入的缓存控制字段,常用的值有:

在Node.js中,可以通过设置响应头来实现强缓存:

const http = require('http');

http.createServer((req, res) => {
  res.setHeader('Cache-Control', 'public, max-age=3600'); // 缓存1小时
  res.end('Hello, World!');
}).listen(3000, () => {
  console.log('Server is running on port 3000');
});

2.2 使用Expires

Expires是HTTP/1.0中引入的缓存控制字段,用于指定资源的过期时间。它的值是一个GMT格式的日期字符串。

const http = require('http');

http.createServer((req, res) => {
  const expiresDate = new Date(Date.now() + 3600 * 1000).toUTCString();
  res.setHeader('Expires', expiresDate); // 缓存1小时
  res.end('Hello, World!');
}).listen(3000, () => {
  console.log('Server is running on port 3000');
});

需要注意的是,Expires的优先级低于Cache-Control,因此在现代Web开发中,推荐使用Cache-Control

3. 协商缓存的实现

协商缓存主要通过ETagLast-Modified两个字段来实现。

3.1 使用ETag

ETag是服务器为资源生成的唯一标识符。当资源发生变化时,ETag也会随之改变。浏览器在请求资源时,会携带If-None-Match头,其值为上次请求时服务器返回的ETag。服务器通过比较If-None-Match和当前资源的ETag来判断资源是否更新。

在Node.js中,可以通过计算资源的哈希值来生成ETag

const http = require('http');
const crypto = require('crypto');

const generateETag = (content) => {
  return crypto.createHash('md5').update(content).digest('hex');
};

http.createServer((req, res) => {
  const content = 'Hello, World!';
  const etag = generateETag(content);

  if (req.headers['if-none-match'] === etag) {
    res.statusCode = 304;
    res.end();
  } else {
    res.setHeader('ETag', etag);
    res.end(content);
  }
}).listen(3000, () => {
  console.log('Server is running on port 3000');
});

3.2 使用Last-Modified

Last-Modified是服务器返回的资源最后修改时间。浏览器在请求资源时,会携带If-Modified-Since头,其值为上次请求时服务器返回的Last-Modified。服务器通过比较If-Modified-Since和当前资源的最后修改时间来判断资源是否更新。

在Node.js中,可以通过设置Last-Modified头来实现协商缓存:

const http = require('http');
const fs = require('fs');

http.createServer((req, res) => {
  const filePath = './resource.txt';
  const stats = fs.statSync(filePath);
  const lastModified = stats.mtime.toUTCString();

  if (req.headers['if-modified-since'] === lastModified) {
    res.statusCode = 304;
    res.end();
  } else {
    res.setHeader('Last-Modified', lastModified);
    const content = fs.readFileSync(filePath);
    res.end(content);
  }
}).listen(3000, () => {
  console.log('Server is running on port 3000');
});

4. 强缓存与协商缓存的结合使用

在实际开发中,通常会将强缓存和协商缓存结合使用。首先通过强缓存减少服务器请求,当强缓存失效时,再通过协商缓存验证资源是否更新。

const http = require('http');
const fs = require('fs');
const crypto = require('crypto');

const generateETag = (content) => {
  return crypto.createHash('md5').update(content).digest('hex');
};

http.createServer((req, res) => {
  const filePath = './resource.txt';
  const stats = fs.statSync(filePath);
  const lastModified = stats.mtime.toUTCString();
  const content = fs.readFileSync(filePath);
  const etag = generateETag(content);

  res.setHeader('Cache-Control', 'public, max-age=3600'); // 强缓存1小时
  res.setHeader('Last-Modified', lastModified);
  res.setHeader('ETag', etag);

  if (req.headers['if-none-match'] === etag || req.headers['if-modified-since'] === lastModified) {
    res.statusCode = 304;
    res.end();
  } else {
    res.end(content);
  }
}).listen(3000, () => {
  console.log('Server is running on port 3000');
});

5. 总结

通过合理使用强缓存和协商缓存,可以显著提升Web应用的性能。强缓存适用于那些不经常变化的静态资源,而协商缓存则适用于那些可能会频繁更新的资源。在实际开发中,应根据资源的特点选择合适的缓存策略,并结合使用Cache-ControlExpiresETagLast-Modified等字段来实现高效的缓存机制。

推荐阅读:
  1. 分布式缓存:缓存雪崩+缓存穿透+缓存预热+缓存更新+缓存降级
  2. 如何使用node解读http缓存的内容

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

node

上一篇:IDEA类存在但找不到如何解决

下一篇:Vue3中toRef和toRefs函数怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》