မကြာခဏ ဖတ်တဲ့ Result ကို Cache ထားပါ
12.6.0
ထပ်တွက်ရတာ သက်သာဖို့ result ကို ခဏသိမ်းပါ။ ဘယ်အချိန် database ကနေ အသစ်ပြန်ဖတ်မလဲ စည်းမျဉ်း သတ်မှတ်ပါ။
Code စမ်းလို့ရတဲ့ သင်ခန်းစာ ဖွင့်ရန်
ဒီစာမျက်နှာမှာ
Cache အရင်ဖတ်ပြီး Database ဖတ်ပါ
@nestjs/cache-manager နဲ့ cache-manager install လုပ်ပြီး CacheModule register လုပ်ပါ။ Service ထဲမှာ CACHE_MANAGER inject လုပ်ပါ။ Default store က memory ထဲမှာပါ။ ဒီနမူနာမှာ key က shop ကို ခွဲပြီး result ကို 30,000 milliseconds သိမ်းပါတယ်။
// Inside the service with CACHE_MANAGER and a product repository injected
async list(shopId: number) {
const key = "products:shop:" + shopId;
const cached = await this.cache.get<Product[]>(key);
if (cached != null) return cached;
const products = await this.repository.list(shopId);
await this.cache.set(key, products, 30_000);
return products;
}
Write ပြီးရင် Entry အဟောင်း ဖယ်ပါ
Database commit ပြီးရင် သက်ဆိုင်ရာ key ဖျက်ပါ။ ဒါဆို နောက်တစ်ခါဖတ်တဲ့အခါ data အသစ်ယူနိုင်ပါတယ်။ လုပ်နေဆဲ read က data အဟောင်း ပြန်သိမ်းနိုင်သေးလို့ TTL တိုတိုထားပါ။ ချက်ချင်းမှန်ဖို့လိုတဲ့ data အတွက် ပိုသေချာတဲ့ design သုံးပါ။ Nest process အများကြီးက တူညီတဲ့ cache values သုံးဖို့လိုရင် shared store ရွေးပါ။
await this.repository.updateQuantity(shopId, productId, quantity);
await this.cache.del("products:shop:" + shopId);