Table of Contents
Caching principle
Strong cache
koa implements strong Cache
Negotiation cache (the browser and the server negotiate and judge by a value)
The difference between negotiated cache ETag and Last-Modified:
koa implements negotiation cache
koa uses hash to calculate Etag value:
Cache execution process :
The use of strong cache and negotiated cache?
Conclusion
Home Web Front-end JS Tutorial What is cache? How to implement it using node?

What is cache? How to implement it using node?

Mar 06, 2023 pm 07:33 PM
front end node.js interview

Browser caching is an important direction in front-end optimization. By caching static resources, the loading time of the page can be reduced, the load on the server can be reduced, and the user experience can be improved. This article will introduce the basic principles of browser caching and common caching strategies, and implement them using code under the koa framework of nodejs.

What is cache? How to implement it using node?

Caching principle

The basic principle of browser caching is to cache static resources (such as CSS, JavaScript, images, etc.) Local, when the page requests these resources again, they are obtained directly from the local instead of downloading them from the server again. This can reduce page loading time and reduce server load, improving user experience.

In the HTTP protocol, browser caching can be implemented through two mechanisms: strong caching and negotiated caching. [Related tutorial recommendations: nodejs video tutorial]

Strong cache

  • Expires field:

    • The value is the expiration time returned by the server, which may cause cache hit errors due to different times between the server and the client
  • Cache-Control (alternative)

    • public: All content is cached (both clients and proxy servers can be cached)

    • private: Only cached to private cache ( Client)

    • no-cache: Confirm with the server whether the returned response has been changed before using the response to satisfy subsequent requests for the same URL. Therefore, if the appropriate validation token (ETag) is present, no-cache initiates a round-trip communication to validate the cached response, and can avoid downloading if the resource has not been changed.

    • no-store: The value is not cached

    • must-revalidation/proxy-revalidation: If the cached content is invalidated, the request must be sent to the server Re-authentication

    • max-age=xxx: The cached content will expire after xxx seconds. This option can only be used in http1.1, than last-Modified Higher priority

  • last-Modified (last modified date)

    • last-Modified: Saved on the server , record the date when the resource was last modified (it cannot be accurate to seconds. If it is modified multiple times within a few seconds, it may cause an error to hit the cache)

    • if-modified-since: Save In the client, the request is carried and compared with the last-Modified of the server. If it is the same, it will directly hit the cache and return the 304 status code

koa implements strong Cache

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'));
Copy after login

Negotiation cache (the browser and the server negotiate and judge by a value)

  • Etag/if-None-Match

    • Etag: The server calculates a hash value (it can also be other algorithms, representing a resource identifier) ​​based on the requested resource and returns it to the browser. The next time the browser When requesting the resource, send Etag to the server through the if-None-Match field

  • Last_Modified and if- Modified-Since

    • last-Modified: Saved in the server, records the date when the resource was last modified (it cannot be accurate to seconds. If it is modified multiple times within a few seconds, it may cause errors. Hit cache)

    • if-modified-since: Saved in the client, the request is carried and compared with the last-Modified of the server. If the same, the cache will be directly hit and a 304 status code will be returned.

The difference between negotiated cache ETag and Last-Modified:

  • ETag is the unique identifier assigned by the server to the resource, and Last-Modified is the last modified time of the resource as reported by the server.

  • ETag can be generated using any algorithm, such as hashing, while Last-Modified can only use a specific time format (GMT). The comparison of

  • ETag is a strong validator (exact-match validator) and requires an exact match, while the comparison of Last-Modified is a weak The validator (weak validator) only needs to be the same within the same second.

  • ETag is suitable for all types of resources, while Last-Modified is only suitable for resources that change infrequently, such as pictures, videos, etc. .

For resources that are updated frequently, ETag is more suitable because it can more accurately detect whether the resource has been modified; while for resources that are not updated frequently, Last-Modified is more suitable because It reduces server load and network traffic.

koa implements negotiation cache

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'));
Copy after login

koa uses hash to calculate Etag value:

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);
Copy after login

Cache execution process :

  • The strong cache has not expired, data is read from the cache, cache-control priority is higher than last-Modified

  • ## The strong cache is invalid, negotiation cache is executed, and the priority of Etag will be higher than last-Modified

  • The server returns a 304 status code if the cache is not invalidated, and the client reads data from the cache

  • If the cache is invalidated, resources and a 200 status code are returned

The use of strong cache and negotiated cache?

Strong cache usually caches static resources (such as CSS, JavaScript, images, etc.) in the browser to reduce the loading time of the page and reduce the load on the server.

Negotiation cache is usually used to cache dynamic resources (such as HTML pages, API data, etc.) to reduce the load on the server and the consumption of network bandwidth.

In actual applications, strong caching and negotiation caching can be used alone or together. For some static resources, you can only use strong caching; for some dynamic resources, you can only use negotiation caching; for some frequently changing resources, you can use strong caching and negotiation caching in combination, which can not only reduce the load on the server, but also ensure timeliness. Get the latest resources.

Conclusion

Although it is implemented using back-end nodejs, I think the front-end should also know more or less about this knowledge so that the back-end can better understand it. to interact. How to implement the front-end will be discussed later?

For more node-related knowledge, please visit: nodejs tutorial!

The above is the detailed content of What is cache? How to implement it using node?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

C# development experience sharing: front-end and back-end collaborative development skills C# development experience sharing: front-end and back-end collaborative development skills Nov 23, 2023 am 10:13 AM

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

How to implement instant messaging on the front end How to implement instant messaging on the front end Oct 09, 2023 pm 02:47 PM

Methods for implementing instant messaging include WebSocket, Long Polling, Server-Sent Events, WebRTC, etc. Detailed introduction: 1. WebSocket, which can establish a persistent connection between the client and the server to achieve real-time two-way communication. The front end can use the WebSocket API to create a WebSocket connection and achieve instant messaging by sending and receiving messages; 2. Long Polling, a technology that simulates real-time communication, etc.

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Golang framework interview questions collection Golang framework interview questions collection Jun 02, 2024 pm 09:37 PM

The Go framework is a set of components that extend Go's built-in libraries, providing pre-built functionality (such as web development and database operations). Popular Go frameworks include Gin (web development), GORM (database operations), and RESTful (API management). Middleware is an interceptor pattern in the HTTP request processing chain and is used to add functionality such as authentication or request logging without modifying the handler. Session management maintains session status by storing user data. You can use gorilla/sessions to manage sessions.

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

See all articles