Home » quick thoughts

Mali caching servis

22. srpanj 2009 by Hudo 0 Komentari

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 , 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?

Bookmark and Share


Komentari

Dodaj komentar




Click to change captcha
biuquote
  • Komentar
  • Preview
Loading