使用 Fastify 和 Redis 快取加速您的網站

不到 24 小時前,我寫了一篇關於如何使用 Cloudflare 快取加速您的網站的文章。不過,我已經將大部分邏輯轉移到使用 Redis 的 Fastify 中間件。以下是您自己操作的原因和方法。
Cloudflare 快取問題
我遇到了 Cloudflare 快取的兩個問題:
- 啟用回應快取後頁面導航中斷。不久前我在 Remix 論壇上提出了一個有關此問題的問題,但截至撰寫本文時,該問題仍未解決。目前尚不清楚為什麼快取回應會導致頁面導航中斷,但只有當 Cloudflare 快取回應時才會發生這種情況。
- 我無法讓 Cloudflare 按照原始帖子中的描述執行重新驗證時提供陳舊內容。看起來這不是可用的功能。
我還遇到了一些其他問題(例如無法使用模式匹配清除快取),但這些對我的用例來說並不重要。
因此,我決定將邏輯轉移到使用 Redis 的 Fastify 中間件。
[!注意]
我將 Cloudflare 快取留給映像快取。在這種情況下,Cloudflare 快取有效地充當 CDN。
Fastify 中介軟體
以下是我使用 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<string, string>;
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<string> => {
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<string, string>;
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;
});
註解貫穿了程式碼,但這裡有一些關鍵點:
- 快取標準:
- 請求:
- 不要快取經過驗證的使用者的回應。
- 僅快取 GET 請求。
- 僅快取包含「/supplements/」的 URL 的回應。
- 如果請求頭包含cache-control: no-cache,則繞過快取。
- 回覆:
- 僅快取成功的回應(statusCode 為 200)。
- 不要快取已經從快取提供的回應(x-pillser-cache:HIT)。
- 僅快取內容類型為:text/html 的回應。
- 快取金鑰產生:
- 使用包含請求方法、URL 和視口寬度的 JSON 表示形式的 SHA-256 雜湊。
- 在快取鍵前加上「request:」前綴,以便於命名空間和清除。
- 請求處理:
- 掛鉤 onRequest 生命週期以檢查請求是否有快取的回應。
- 提供快取的回應(如果可用),並使用 x-pillser-cache: HIT 進行標記。
- 發送快取回應後啟動後台任務刷新緩存,實現「重新驗證時提供陳舊內容」。
- 響應處理:
- 掛鉤 onSend 生命週期來處理和快取回應。
- 將可讀流轉換為字串以簡化快取。
- 從快取中排除特定標頭(content-length、set-cookie、x-pillser-cache)。
- 將不可緩存的回應標記為 x-pillser-cache: DYNAMIC。
- 以一天的 TTL(生存時間)快取回應,用 x-pillser-cache: MISS 標記新條目。
結果
我從多個位置運行了延遲測試,並捕獲了每個 URL 的最慢響應時間。結果如下:
| URL | Country | Origin Response Time | Cloudflare Cached Response Time | Fastify Cached Response Time |
|---|---|---|---|---|
| https://pillser.com/vitamins/vitamin-b1 | us-west1 | 240ms | 16ms | 40ms |
| https://pillser.com/vitamins/vitamin-b1 | europe-west3 | 320ms | 10ms | 110ms |
| https://pillser.com/vitamins/vitamin-b1 | australia-southeast1 | 362ms | 16ms | 192ms |
| https://pillser.com/supplements/vitamin-b1-3254 | us-west1 | 280ms | 10ms | 38ms |
| https://pillser.com/supplements/vitamin-b1-3254 | europe-west3 | 340ms | 12ms | 141ms |
| https://pillser.com/supplements/vitamin-b1-3254 | australia-southeast1 | 362ms | 14ms | 183ms |
與 Cloudflare 快取相比,Fastify 快取速度較慢。這是因為快取的內容仍然是從來源提供的,而 Cloudflare 快取是從區域邊緣位置提供的。然而,我發現這些回應時間足以實現良好的使用者體驗。
以上是使用 Fastify 和 Redis 快取加速您的網站的詳細內容。更多資訊請關注PHP中文網其他相關文章!
熱AI工具
Undress AI Tool
免費脫衣圖片
Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片
AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。
Clothoff.io
AI脫衣器
Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!
熱門文章
熱工具
記事本++7.3.1
好用且免費的程式碼編輯器
SublimeText3漢化版
中文版,非常好用
禪工作室 13.0.1
強大的PHP整合開發環境
Dreamweaver CS6
視覺化網頁開發工具
SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)
如何在JS中與日期和時間合作?
Jul 01, 2025 am 01:27 AM
JavaScript中的日期和時間處理需注意以下幾點:1.創建Date對像有多種方式,推薦使用ISO格式字符串以保證兼容性;2.獲取和設置時間信息可用get和set方法,注意月份從0開始;3.手動格式化日期需拼接字符串,也可使用第三方庫;4.處理時區問題建議使用支持時區的庫,如Luxon。掌握這些要點能有效避免常見錯誤。
為什麼要將標籤放在的底部?
Jul 02, 2025 am 01:22 AM
PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl
什麼是在DOM中冒泡和捕獲的事件?
Jul 02, 2025 am 01:19 AM
事件捕獲和冒泡是DOM中事件傳播的兩個階段,捕獲是從頂層向下到目標元素,冒泡是從目標元素向上傳播到頂層。 1.事件捕獲通過addEventListener的useCapture參數設為true實現;2.事件冒泡是默認行為,useCapture設為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委託,提高動態內容處理效率;5.捕獲可用於提前攔截事件,如日誌記錄或錯誤處理。了解這兩個階段有助於精確控制JavaScript響應用戶操作的時機和方式。
如何減少JavaScript應用程序的有效載荷大小?
Jun 26, 2025 am 12:54 AM
如果JavaScript應用加載慢、性能差,問題往往出在payload太大,解決方法包括:1.使用代碼拆分(CodeSplitting),通過React.lazy()或構建工具將大bundle拆分為多個小文件,按需加載以減少首次下載量;2.移除未使用的代碼(TreeShaking),利用ES6模塊機制清除“死代碼”,確保引入的庫支持該特性;3.壓縮和合併資源文件,啟用Gzip/Brotli和Terser壓縮JS,合理合併文件並優化靜態資源;4.替換重型依賴,選用輕量級庫如day.js、fetch
JavaScript模塊上的確定JS綜述:ES模塊與COMPORJS
Jul 02, 2025 am 01:28 AM
ES模塊和CommonJS的主要區別在於加載方式和使用場景。 1.CommonJS是同步加載,適用於Node.js服務器端環境;2.ES模塊是異步加載,適用於瀏覽器等網絡環境;3.語法上,ES模塊使用import/export,且必須位於頂層作用域,而CommonJS使用require/module.exports,可在運行時動態調用;4.CommonJS廣泛用於舊版Node.js及依賴它的庫如Express,ES模塊則適用於現代前端框架和Node.jsv14 ;5.雖然可混合使用,但容易引發問題
如何在node.js中提出HTTP請求?
Jul 13, 2025 am 02:18 AM
在Node.js中發起HTTP請求有三種常用方式:使用內置模塊、axios和node-fetch。 1.使用內置的http/https模塊無需依賴,適合基礎場景,但需手動處理數據拼接和錯誤監聽,例如用https.get()獲取數據或通過.write()發送POST請求;2.axios是基於Promise的第三方庫,語法簡潔且功能強大,支持async/await、自動JSON轉換、攔截器等,推薦用於簡化異步請求操作;3.node-fetch提供類似瀏覽器fetch的風格,基於Promise且語法簡單
編寫清潔和可維護的JavaScript代碼的最佳實踐是什麼?
Jun 23, 2025 am 12:35 AM
要寫出乾淨、可維護的JavaScript代碼,應遵循以下四點:1.使用清晰一致的命名規範,變量名用名詞如count,函數名用動詞開頭如fetchData(),類名用PascalCase如UserProfile;2.避免過長函數和副作用,每個函數只做一件事,如將更新用戶信息拆分為formatUser、saveUser和renderUser;3.合理使用模塊化和組件化,如在React中將頁面拆分為UserProfile、UserStats等小組件;4.寫註釋和文檔時點到為止,重點說明關鍵邏輯、算法選
var vs Let vs const:快速JS綜述解釋器
Jul 02, 2025 am 01:18 AM
var、let和const的區別在於作用域、提升和重複聲明。 1.var是函數作用域,存在變量提升,允許重複聲明;2.let是塊級作用域,存在暫時性死區,不允許重複聲明;3.const也是塊級作用域,必須立即賦值,不可重新賦值,但可修改引用類型的內部值。優先使用const,需改變變量時用let,避免使用var。


