1.1 กำหนดระยะเวลาเก็บ cache ไว้ที่ 25 นาที
นาย ก เปิดใช้งานหน้าเว็บในวันนี้เป็นคนแรกที่เวลา 9.00 จะไม่มี cache จึงไป query ข้อมูลมาจาก DB และเก็บค่าใช้ใน cache เป็นเวลา 25 นาที ทำงานจนเสร็จปิดหน้าจอออกไป
นาย ก เปิดหน้าเว็บเดิม เวลา 9.05 นาที ระบบจะเช็คจาก cache ก่อนว่ามีหรือไม่ พบว่ามี เรียกใช้ค่าจาก cache
นาย ข เปิดหน้าเว็บ เวลา 9.15 ระบบจะเช็คจาก cache ก่อนว่ามีหรือไม่ พบว่ามี จึ่งเรียกใช้ค่าจาก cache
นาย ค เปิดหน้าเว็บ เวลา 10.00 ระบบจะเช็คจาก cache ก่อนว่ามีหรือไม่ พบว่า ไม่มี จึงไป query ข้อมูลมาจาก DB และเก็บค่าใช้ใน cache เป็นเวลา 25 นาที
ทำงานในลักษณะนี้ไปเรื่อยๆ ลดการ access เข้า database ในทุกๆครั้ง
โค้ด: เลือกทั้งหมด
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;
using System.Web;
using System.Web.Mvc;
namespace Common.Utils
{
public class CacheManager
{
private static ObjectCache Cache = MemoryCache.Default;
private static double CacheTimeInMinutes = 25;
public static object GetObjectCache(string key)
{
return Cache.Get(key);
}
public static void SetObjectCache(string key, object objectValue)
{
CacheItemPolicy policy = new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(CacheTimeInMinutes)
};
Cache.Set(key, objectValue, policy);
}
public static List<SelectListItem> getDropdownListCache(string key)
{
var dropdownCache = Cache.Get(key) as List<SelectListItem>;
if (dropdownCache != null)
return new List<SelectListItem>(dropdownCache);
return dropdownCache;
}
}
}
โค้ด: เลือกทั้งหมด
using Common.Utils;
public JsonResult GetGenderDropDownList()
{
try
{
List<SelectListItem> result = this.GetDropdownList("Gender");
return Json(result, JsonRequestBehavior.DenyGet);
}
catch
{
throw;
}
}
public List<SelectListItem> GetDropdownList(string type)
{
try
{
List<SelectListItem> lstResult = null;
List<SelectListItem> lstResultCache = null;
//check cache
var cacheKey = + "cache|" + type;
lstResultCache = CacheManager.GetObjectCache(cacheKey) as List<SelectListItem>;
if (lstResultCache == null)
{
switch (type)
{
case Gender:
lstResult = GetGenderDropdownList();
break;
case Country:
lstResult = GetCountryDropdownList();
break;
case Marital:
lstResult = GetMaritalStatusDropdownList();
break;
}
if (lstResult != null)
{
lstResult.Insert(0, new SelectListItem() { Text = "", Value = "", Selected = true });
CacheManager.SetObjectCache(cacheKey, lstResult);
}
return lstResult;
}
else
{
return lstResultCache;
}
}
catch
{
throw;
}
}