百度云加速新出的邊緣計算功能確實不錯,可操作性非常強。今天我們來學(xué)習(xí)下如何利用這個功能給網(wǎng)站做緩存。
首先我們先創(chuàng)建函數(shù),在我們的控制臺左邊,我的函數(shù),添加
函數(shù)名隨便寫
輸入代碼保存,代碼如下:
async function handleRequest(event) { const { request } = event // POST請求不緩存 if (request.method.toUpperCase() === 'POST') return await fetch(request) // 創(chuàng)建cacheKey let cacheUrl = new URL(request.url) let cacheKey = new Request(cacheUrl, request) let cache = caches.default // 查找是否該cacheKey已緩存 let response = await cache.match(cacheKey) // 如果沒緩存則加入到緩存 if (!response) { response = await fetch(request) response = new Response(response.body, response) // 添加過期時間 response.headers.append('Cache-Control', 'max-age=10') // 加入到緩存 event.waitUntil(cache.put(cacheKey, response.clone())) } return response } addEventListener('fetch', event => { return event.respondWith(handleRequest(event)) }) 再返回控制臺,我的網(wǎng)站,進入域名管理,左邊的邊緣計算添加觸發(fā)規(guī)則,選擇剛才添加的函數(shù)名,確認即可
匹配內(nèi)容寫你要緩存的URL地址加通配符,即可完成。
URL 匹配規(guī)則說明:
規(guī)則綁定形如:?https://*.example.com/images/*
一般規(guī)則:
1、規(guī)則里必須包含域名,如example.com/1.jpg。
2、規(guī)則里不能包含參數(shù),如example.com/?anything是不合法的。
3、規(guī)則中如果不包含協(xié)議,則會匹配http和https;如果指定協(xié)議,則只匹配指定的協(xié)議。如www.example.com/會同時匹配https://www.example.com/和http://www.example.com/,https://www.example.com/只匹配https://www.example.com/而不會匹配http://www.example.com/。
關(guān)于通配符「*」:
1、僅支持通配符,代表0個或多個任意字符。
*不能用于中綴或參數(shù)的匹配,如example.com/*.jpg或example.com/?foo=*都是不合法的。
2、多條規(guī)則都匹配時,優(yōu)先匹配更精確的規(guī)則,如www.example.com/*的匹配優(yōu)先級高于*.example.com/*。
3、*匹配前綴時,*example.com/會同時匹配https://example.com/和https://www.example.com/;*.example.com/只會匹配https://www.example.com/而不匹配https://example.com/。
4、*匹配后綴時,https://example.com/path*,會同時匹配https://example.com/path2和https://example.com/path/readme.txt;https://example.com/path/*,則只匹配https://example.com/path/readme.txt而不匹配https://example.com/path2。