หลายๆคนที่ใช้ CloudFlare อยู่ก็คนจะได้ใช้หลายๆฟังชั่นของ CloudFlare แล้ว
แต่ก็ยังมีอีกหลายๆคนที่อาจจะยังไม่เคยใช้ CloudFlare Worker ชึ่งสามารถเอามาประยุคใช้งานได้หลายอย่าง ไม่ว่าจะเป็นการ สั่งให้ทำอะไรบางอย่างก็ส่งข้อมูลจริงออกไป หรือแม้แต่เอามาทำ Cache ด้วย Worker (Server Cache) ด้วย Code ต่อไปนี้
- วิธีนี้เหมาะกับ Server ต่างประเทศที่โหลดช้ามากๆ
- เว็บไชต์ประเภท Static Page
- เว็บไชต์หรือ API ที่ไม่ได้เปลี่ยนแปลงบ่อยๆ
async function handleRequest(event) {
const cache = caches.default;
const cacheKey = new Request(event.request);
let response = await cache.match(cacheKey);
if (!response) {
console.log("cache")
// If response is not in cache, fetch it from the origin server
response = await fetch(event.request);
// Clone the response with its headers and metadata, but not the body
response = new Response(response.body, response);
// Cache the response for future requests with a specific max-age
const cacheHeaders = new Headers(response.headers);
cacheHeaders.append("Cache-Control", "max-age=3600"); // Cache the response for 1 hour (3600 seconds)
response = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: cacheHeaders,
});
event.waitUntil(cache.put(cacheKey, response.clone()));
}else{
console.log("not cache")
}
return response;
}
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event));
});
วิธีติดตั้งก็ง่ายๆเลยครับ ทำตามขั้นตอนต่อไปนี้ได้เลย
- ไปที่เมนู Wokers & Pages เลือก Overview
- จากนั้นกด Create Worker

- จากนั้นจะมีหน้าจอตัวอย่าง Code ขึ้นมา
- ให้กด Deploy ได้เลย

- จากนั้นกดไปที่ปุ่ม Edit Code

- จากนั้นนำ Code ที่ผู้เขียนแตรียมไว้ให้ไปวางดังรูป
- จากนั้นกด Save and Deploy
- แล้วกดย้อนกลับ ไปที่ โปรเจ็ค Worker ของเราได้เลยครับ ในที่นี่คือ hello-world-**

- จากนั้นกดไปที่ Add route ภายใต้หัวข้อ Trigger
- จากนั้นใส่ Domain ที่ต้องการให้ Worker Cache ไว้ เช่น devdog.blog/* ดังภาพ
- และทำการกด Add route

- ไปที่เมนู Logs แล้วกด Begin log stream
- จากนั้นลองทดสอบเข้าเว็บไชต์ดูครับ

- จะแสดงผล URL เข้าเว็บเราขึ้นมา พร้อมบอก message ว่า cache

เป็นอันจบครับ
** วิธีนี้อาจจะเหมาะกับผู้ที่ใช้ Server ต่างประเทศที่มีระยะเวลาโหลดจาก Server ช้าก็เปลี่ยนมา Cache บน Woker ก่อนแล้วค่อยส่งต่อไปหาผู้ใช้งานครับ เช่น Server ของผู้เขียนที่เป็น wordpress hosting ที่ค่อนข้างช้า
ก่อนใช้ Worker Cache 2.14 วินาที

หลังใช้ Woker Cache 0.31 วินาที (313ms)

*** ข้อควรระวังคือ woker ตัวฟรี มีข้อจำกัดนะครับ สามารถเรียกใช้งานได้เพียงวันละ 100,000 ครั้งเท่านั้น
