浏览器缓存是一种用于提高网页加载速度和减轻服务器负载的技术。在服务器端,开发人员可以通过设置 HTTP 响应头来控制浏览器如何缓存和重新获取资源。本文将介绍如何在服务器端管理浏览器缓存,并提供相应的源代码示例。
- 设置缓存过期时间
通过设置合适的缓存过期时间,可以告诉浏览器在多长时间内可以直接使用缓存的资源,而无需重新从服务器获取。这可以通过设置 “Cache-Control” 和 “Expires” 响应头来实现。
示例代码(Node.js):
const http = require('http');
const server = http.createServer((req, res) => {
// 设置缓存过期时间为一小时
const oneHour = 60 * 60;
res.setHeader('Cache-Control', `public, max-age=${oneHour}`);
res.setHeader('Expires', new Date(Date.now() + oneHour * 1000).toUTCString());
// 其他响应设置和处理逻辑
// ...
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
在上面的示例中,我们设置了 “Cache-Control” 响应头为 “public, max-age=3600”,表示资源是公共的,可以被缓存,并且缓存有效期为一小时。同时,我们还设置了 “Expires” 响应头为当前时间加上一小时的时间戳。
- 缓存验证
有时候,即使资源的缓存过期时间尚未到达,服务器仍然希望对资源进行验证,以确保客户端缓存的资源仍然是最新的。这可以通过设置 “ETag” 和 “Last-Modified” 响应头来实现。
示例代码(Node.js):
const http = require('http');
const crypto = require('crypto');
const server = http.createServer((req, res) => {
// 生成资源的哈希值作为 ETag
const fileContent = '...'; // 从文件中读取资源内容
const hash = crypto.createHash('md5').update(fileContent).digest('hex');
const etag = `"${hash}"`;
// 设置 ETag 和 Last-Modified 响应头
res.setHeader('ETag', etag);
res.setHeader('Last-Modified', new Date(fileLastModified).toUTCString());
// 检查客户端发送的 If-None-Match 和 If-Modified-Since 请求头
const ifNoneMatch = req.headers['if-none-match'];
const ifModifiedSince = req.headers['if-modified-since'];
if (ifNoneMatch === etag && ifModifiedSince === new Date(fileLastModified).toUTCString()) {
// 资源未发生变化,返回 304 Not Modified
res.statusCode = 304;
res.end();
} else {
// 资源已更新,返回新的资源
res.statusCode = 200;
res.end(fileContent);
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
在上面的示例中,我们首先生成资源内容的哈希值作为 ETag,并将其设置为响应头。同时,我们还设置了 “Last-Modified” 响应头为资源的最后修改时间。
当客户端发送请求时,服务器会检查请求中的 “If-None-Match” 和 “If-Modified-Since” 头与当前资源的 ETag 和最后修改时间是否匹配。如果匹配,表示资源未发生变化,服务器返回 304 Not Modified 响应;否则,服务器返回新的资源。
- 强制缓存
除了以上提到的设置缓存过期时间和缓存验证外,服务器还可以通过设置 “Cache-Control” 响应头来强制浏览器缓存资源,即使资源已经过期。
示例代码(Node.js):
const http = require('http');
const server = http.createServer((req, res) => {
// 设置缓存过期时间为一周
const oneWeek = 7 * 24 * 60 * 60;
res.setHeader('Cache-Control', `public, max-age=${oneWeek}`);
// 其他响应设置和处理逻辑
// ...
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
在上面的示例中,我们将 “Cache-Control” 响应头设置为 “public, max-age=604800”,表示资源可以被公共缓存,并且缓存有效期为一周。
总结:
通过在服务器端设置适当的响应头,开发人员可以有效地管理浏览器缓存。设置缓存过期时间、缓存验证和强制缓存等策略可以显著提高网页加载速度,并减轻服务器负载。请根据实际需求选择适当的缓存管理策略,并根据服务器端框架和语言进行相应的实现。