400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

用node如何实现缓存

本文小编为大家详细介绍“用node如何实现缓存”,内容详细,步骤清晰,细节处理妥当,希望这篇“用node如何实现缓存”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

站在用户的角度思考问题,与客户深入沟通,找到会同网站设计与会同网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站设计、网站制作、企业官网、英文网站、手机端网站、网站推广、域名与空间、网页空间、企业邮箱。业务覆盖会同地区。

缓存原理

浏览器缓存的基本原理是将静态资源(如 CSS、JavaScript、图片等)缓存到本地,当页面再次请求这些资源时,直接从本地获取,而不是重新从服务器下载。这可以减少页面的加载时间和减轻服务器负担,提高用户体验。

在 HTTP 协议中,浏览器缓存可以通过两种机制实现:强缓存和协商缓存。

强缓存

koa实现强缓存

const Koa = require('koa');
const app = new Koa();

// 设置 expires方案
const setExpires = async (ctx, next) => {
  // 设置缓存时间为 1 分钟
  const expires = new Date(Date.now() + 60 * 1000);
  ctx.set('Expires', expires.toUTCString());
  await next();
}
// Cache-Control方案(优先执行)
const setCacheControl = async (ctx, next) => {
  // 设置缓存时间为 1 分钟
  ctx.set('Cache-Control', 'public, max-age=60');
  await next();
}
// Last-Modified方案
const setLastModified = async (ctx, next) => {
  // 获取资源最后修改时间
  const lastModified = new Date('2021-03-05T00:00:00Z');
  // 设置 Last-Modified 头
  ctx.set('Last-Modified', lastModified.toUTCString());
  await next();
}

const response = (ctx) => {
  ctx.body = 'Hello World';
}

// 跟Last-Modified方案相对应
const lastModifiedResponse = (ctx) => {
  // 如果资源已经修改过,则返回新的资源
  if (ctx.headers['if-modified-since'] !== ctx.response.get('Last-Modified')) {
    	response(ctx)
  } else ctx.status = 304;
}

app.get('/getMes', setExpires, response);

app.listen(3000, () => console.log('Server started on port 3000'));

协商缓存(浏览器和服务器通过一个值进行协商判断)

用node如何实现缓存

协商缓存ETag和Last-Modified区别:

对于经常更新的资源,ETag 更适合,因为它可以更准确地检测资源是否已经被修改;而对于不经常更新的资源,Last-Modified 更适合,因为它可以减少服务器负载和网络流量。

koa实现协商缓存

const Koa = require('koa');
const app = new Koa();

// 设置 eTag方案
const setExpires = async (ctx, next) => {
  // 设置缓存时间为 1 分钟
  const maxAge = 60;
  ctx.set('Cache-Control', `public, max-age=${maxAge}`);
  // 设置 ETag 头
  const etag = 'etag-123456789';
  ctx.set('ETag', etag);

  await next();
}
// Last-Modified方案
const setLastModified = async (ctx, next) => {
  // 设置缓存时间为 1 分钟
  const maxAge = 60;
  ctx.set('Cache-Control', `public, max-age=${maxAge}`);
  // 设置 Last-Modified 头
  const lastModified = new Date('2021-03-05T00:00:00Z');
  ctx.set('Last-Modified', lastModified.toUTCString());

  await next();
}

const response = (ctx) => {
  ctx.body = 'Hello World';
}

// 跟Etag方案对应
const etagResponse = (ctx) => {
  // 如果 ETag 头未被修改,则返回 304
  if (ctx.headers['if-none-match'] === ctx.response.get('ETag')) {
    ctx.status = 304;
  } else ctx.body = 'Hello World';
}
// 跟Last-Modified方案相对应
const lastModifiedResponse = (ctx) => {
  // 如果资源已经修改过,则返回新的资源
  if (ctx.headers['if-modified-since'] !== ctx.response.get('Last-Modified')) {
    	response(ctx)
  } else ctx.status = 304;
}

app.get('/getMes', setExpires, response);

app.listen(3000, () => console.log('Server started on port 3000'));

koa使用哈希计算Etag值:

const Koa = require('koa');
const crypto = require('crypto');

const app = new Koa();

// 假设这是要缓存的资源
const content = 'Hello, world!';

app.use(async (ctx) => {
  // 计算资源的哈希值
  const hash = crypto.createHash('md5').update(content).digest('hex');

  // 设置 ETag 头
  ctx.set('ETag', hash);

  // 判断客户端是否发送了 If-None-Match 头
  const ifNoneMatch = ctx.get('If-None-Match');
  if (ifNoneMatch === hash) {
    // 如果客户端发送了 If-None-Match 头,并且与当前资源的哈希值相同,则返回 304 Not Modified
    ctx.status = 304;
  } else {
    // 如果客户端没有发送 If-None-Match 头,或者与当前资源的哈希值不同,则返回新的资源
    ctx.body = content;
  }
});

app.listen(3000);

缓存执行流程:

强缓存和协商缓存的使用?

强缓存通常在浏览器中缓存静态资源(如 CSS、JavaScript、图片等),以减少页面的加载时间和减轻服务器负担。

协商缓存通常用于缓存动态资源(如 HTML 页面、API 数据等),以减少服务器的负担和网络带宽的消耗。

在实际应用中,强缓存和协商缓存可以单独使用或一起使用。对于一些静态资源,可以只使用强缓存;对于一些动态资源,可以只使用协商缓存;对于一些经常变化的资源,可以使用强缓存和协商缓存结合使用,既可以减少服务器的负担,也可以保证及时获取到最新的资源。

读到这里,这篇“用node如何实现缓存”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注创新互联行业资讯频道。


网页名称:用node如何实现缓存
转载注明:http://www.bluegullmedia.com/article/jppscg.html

其他资讯

让你的专属顾问为你服务

0.0397s