Thuta Learning
ရှာဖွေရန်
IntermediateWeb Developmentintermediate

Cache Components နှင့် Revalidation

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Cache လုပ်သင့်သော data ကိုရွေးရန်
  • use cache နှင့် cacheLife သုံးရန်
  • Tag ဖြင့် တိကျစွာ invalidate လုပ်ရန်

Data ကို request တိုင်း database ကနေပြန်ယူရင် မှန်ကန်ပေမယ့် အကုန်နှေးပြီး ကုန်ကျစရိတ်တက်နိုင်ပါတယ်။ တစ်ဖက်မှာ cache အမြဲထားပြီး မပြန်လဲရင် user က data အဟောင်းမြင်ရပါတယ်။ Cache strategy ဆိုတာ မြန်နှုန်းနဲ့ freshness ကြားက စဉ်းစားဆုံးဖြတ်ချက်ပါ။

နားလည်ထားရမယ့် အချက်

Next.js 16 ရဲ့ Cache Components model ကိုသုံးရန် next.config.ts မှာ cacheComponents ဖွင့်ပါတယ်။ Cache လုပ်မယ့် function ထဲ use cache ထည့်ပြီး cacheLife နဲ့ သက်တမ်းသတ်မှတ်နိုင်ပါတယ်။ cacheTag က data group ကိုနာမည်ပေးပြီး mutation ပြီးချိန် updateTag သို့မဟုတ် revalidateTag နဲ့ တိတိကျကျ ပြန်အသစ်လုပ်နိုင်ပါတယ်။ User တစ်ဦးချင်း secret data သို့မဟုတ် အမြဲလတ်ဆတ်ရမယ့် data ကို မစဉ်းစားဘဲ cache မလုပ်ပါနဲ့။

အတူတူ စမ်းရေးကြည့်မယ်

typescript
// next.config.ts
import type { NextConfig } from "next";
export default { cacheComponents: true } satisfies NextConfig;

// app/lib/notes.ts
import { cacheLife, cacheTag } from "next/cache";

export async function getPublicNotes() {
  "use cache";
  cacheLife("hours");
  cacheTag("notes");
  return db.note.findMany({ where: { published: true } });
}

Code က ဘယ်လိုအလုပ်လုပ်သလဲ

getPublicNotes က တစ်နာရီ profile နဲ့ cache လုပ်ပြီး notes tag ပေးထားပါတယ်။ Note အသစ်ထည့်ပြီးချိန် Server Action က updateTag('notes') ခေါ်ရင် user က ပြောင်းလဲမှုကိုချက်ချင်းမြင်နိုင်ပါတယ်။

You should see
Public notes query ကို cache မှပြန်သုံးပြီး သတ်မှတ်ထားသောအချိန် သို့မဟုတ် tag invalidation အချိန်မှာ အသစ်ယူမည်။

၅ မိနစ် စမ်းကြည့်

Categories list function တစ်ခုကို days profile နဲ့ cache လုပ်ပြီး categories tag ထည့်ပါ။ ဘယ်အချိန် invalidate လုပ်မယ်ဆိုတာ ရေးပါ။

Next.js — RevalidatingNext.js

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • User-specific private data ကို shared cache ထဲထည့်ခြင်း
  • Data ပြောင်းပြီးနောက် သက်ဆိုင်ရာ tag ကို invalidate မလုပ်ခြင်း

လေ့ကျင့်ခန်း

Categories list function တစ်ခုကို days profile နဲ့ cache လုပ်ပြီး categories tag ထည့်ပါ။ ဘယ်အချိန် invalidate လုပ်မယ်ဆိုတာ ရေးပါ။

You'll know it worked when: Public notes query ကို cache မှပြန်သုံးပြီး သတ်မှတ်ထားသောအချိန် သို့မဟုတ် tag invalidation အချိန်မှာ အသစ်ယူမည်။

Cache Components နှင့် Revalidation | Thuta Learning