不到 24 小时前,我写了一篇关于如何使用 Cloudflare 缓存加速您的网站的文章。不过,我已经将大部分逻辑转移到使用 Redis 的 Fastify 中间件中。以下是您自己执行此操作的原因以及方法。
我遇到了 Cloudflare 缓存的两个问题:
我还遇到了一些其他问题(例如无法使用模式匹配清除缓存),但这些对我的用例来说并不重要。
因此,我决定使用 Redis 将逻辑转移到 Fastify 中间件。
[!笔记]
我将 Cloudflare 缓存留给图像缓存。在这种情况下,Cloudflare 缓存有效地充当 CDN。
下面是我使用 Fastify 编写的用于缓存响应的中间件的带注释版本。
const isCacheableRequest = (request: FastifyRequest): boolean => { // Do not attempt to use cache for authenticated visitors. if (request.visitor?.userAccount) { return false; } if (request.method !== 'GET') { return false; } // We only want to cache responses under /supplements/. if (!request.url.includes('/supplements/')) { return false; } // We provide a mechanism to bypass the cache. // This is necessary for implementing the "Serve Stale Content While Revalidating" feature. if (request.headers['cache-control'] === 'no-cache') { return false; } return true; }; const isCacheableResponse = (reply: FastifyReply): boolean => { if (reply.statusCode !== 200) { return false; } // We don't want to cache responses that are served from the cache. if (reply.getHeader('x-pillser-cache') === 'HIT') { return false; } // We only want to cache responses that are HTML. if (!reply.getHeader('content-type')?.toString().includes('text/html')) { return false; } return true; }; const generateRequestCacheKey = (request: FastifyRequest): string => { // We need to namespace the cache key to allow an easy purging of all the cache entries. return 'request:' generateHash({ algorithm: 'sha256', buffer: stringifyJson({ method: request.method, url: request.url, // This is used to cache viewport specific responses. viewportWidth: request.viewportWidth, }), encoding: 'hex', }); }; type CachedResponse = { body: string; headers: Record; statusCode: number; }; const refreshRequestCache = async (request: FastifyRequest) => { await got({ headers: { 'cache-control': 'no-cache', 'sec-ch-viewport-width': String(request.viewportWidth), 'user-agent': request.headers['user-agent'], }, method: 'GET', url: pathToAbsoluteUrl(request.originalUrl), }); }; app.addHook('onRequest', async (request, reply) => { if (!isCacheableRequest(request)) { return; } const cachedResponse = await redis.get(generateRequestCacheKey(request)); if (!cachedResponse) { return; } reply.header('x-pillser-cache', 'HIT'); const response: CachedResponse = parseJson(cachedResponse); reply.status(response.statusCode); reply.headers(response.headers); reply.send(response.body); reply.hijack(); setImmediate(() => { // After the response is sent, we send a request to refresh the cache in the background. // This effectively serves stale content while revalidating. // Therefore, this cache does not reduce the number of requests to the origin; // The goal is to reduce the response time for the user. refreshRequestCache(request); }); }); const readableToString = (readable: Readable): Promise => { const chunks: Uint8Array[] = []; return new Promise((resolve, reject) => { readable.on('data', (chunk) => chunks.push(Buffer.from(chunk))); readable.on('error', (err) => reject(err)); readable.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); }); }; app.addHook('onSend', async (request, reply, payload) => { if (reply.hasHeader('x-pillser-cache')) { return payload; } if (!isCacheableRequest(request) || !isCacheableResponse(reply) || !(payload instanceof Readable)) { // Indicate that the response is not cacheable. reply.header('x-pillser-cache', 'DYNAMIC'); return payload; } const content = await readableToString(payload); const headers = omit(reply.getHeaders(), [ 'content-length', 'set-cookie', 'x-pillser-cache', ]) as Record ; reply.header('x-pillser-cache', 'MISS'); await redis.setex( generateRequestCacheKey(request), getDuration('1 day', 'seconds'), stringifyJson({ body: content, headers, statusCode: reply.statusCode, } satisfies CachedResponse), ); return content; });
注释贯穿了代码,但这里有一些关键点:
我从多个位置运行了延迟测试,并捕获了每个 URL 的最慢响应时间。结果如下:
网址 | 国家 | 原点响应时间 | Cloudflare 缓存响应时间 | Fastify 缓存响应时间 |
---|---|---|---|---|
https://pilser.com/vitamins/vitamin-b1 | us-west1 | 240ms | 16ms | 40ms |
https://pilser.com/vitamins/vitamin-b1 | 欧洲西部3 | 320ms | 10ms | 110ms |
https://pilser.com/vitamins/vitamin-b1 | 澳大利亚-东南部1 | 362ms | 16ms | 192ms |
https://pilser.com/supplements/vitamin-b1-3254 | us-west1 | 280ms | 10ms | 38ms |
https://pilser.com/supplements/vitamin-b1-3254 | 欧洲西部3 | 340ms | 12ms | 141ms |
https://pilser.com/supplements/vitamin-b1-3254 | 澳大利亚-东南部1 | 362ms | 14ms | 183ms |
与 Cloudflare 缓存相比,Fastify 缓存速度较慢。这是因为缓存的内容仍然从源提供服务,而 Cloudflare 缓存则从区域边缘位置提供服务。然而,我发现这些响应时间足以实现良好的用户体验。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3