Mali caching servis
July 22. 2009
1 Comments
- Posted in:
- Quick thoughts
Modificirajući ovaj blog engine (maštovitog imena blogengine.net), primijetio sam da nema ugrađen nikakav caching layer. Da slučajno 10-tak posjetioca bloga dnevno ne bi morali čekati učitavanje, morao sam pod hitno složiti jednostavnu klasu koju mogu upotrijebiti po potrebi bilo gdje u projektu.
Tako je nastalo ovo:
.net framework 2.0 verzija (blogengine.net je u .net 2):
public class CacheService<T> where T:class
{
public delegate T CallbackHandler();
public T Get(string key, CallbackHandler callback,DateTime? expiration)
{
T item = HttpContext.Current.Cache[key] as T;
if (item == null)
{
item = callback() as T;
if(expiration==null)
HttpContext.Current.Cache.Insert(key,item, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
else
HttpContext.Current.Cache.Insert(key, item, null, expiration.Value, Cache.NoSlidingExpiration);
}
return item;
}
}
ili .net 3/3.5 verzija [more], gdje je malo lakše raditi sa delegatima koji vračaju objekt (.net 2 ima dva "predefinirana" delegata, Action, koji je vraća ništa, i Predicate koji vraća bool vrijednost):
public class CacheService
{
public T Get(string key, Func<T> callback,DateTime? expiration) where T:class
{
T item = HttpContext.Current.Cache[key] as T;
if (item == null)
{
item = callback() as T;
if(expiration==null)
HttpContext.Current.Cache.Insert(key,item, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
else
HttpContext.Current.Cache.Insert(key, item, null, expiration.Value, Cache.NoSlidingExpiration);
}
return item;
}
}
Upotreba u .net 2:
CacheService<List<category>> service= new CacheService<List<category>>;
List<category> list = service.Get("cats_menu",
delegate { return Category.Categories; },
DateTime.Now.AddMinutes(5));
i u .net 3/3.5 sa lambda izrazima:
var service= new CacheService();
var list = service.Get("cats_menu",
()=> Category.Categories,
DateTime.Now.AddMinutes(5));
puno ljepše u novom frameworku, zar ne?
Comments
As you get mature, the to locate health conditions will certainly change. Can your alcohol belly bring on medical problems?
penile cancer