appfabric caching instead of querying sql server

350 views Asked by At

I have a table in sql server which I will query many times from the .net MVC code and I want to implement appfabric cache instead of sql server query(only for this query). How do I implement this? If the query is like- select address from people where id = @cid;

cid can be 1,2 or 3 which comes from the code

2

There are 2 answers

2
stuartd On

Whichever cache you use, you would add different cache entries for each query, using a construct of a base key and the ID as the cache key, and the return from the database as the cached value:

public Address GetData(int cId)
{
    const string AddressCacheKeyBase = "AddressCacheKey";
    string key = AddressCacheKeyBase + cId;

    var cachedData = cache.Get(key); 

    if (cachedData != null)
    {   
         return (Address)cachedData;      
    }

    Address address = GetAddressFromDatabase(cID);
    cache.Add(key, address);

    return address;
}
6
Cybermaxs On

Do you really need AppFabric for this scenario ?

I mean, AppFabric Caching targets high volume web sites where database is a bottleneck and local caching is no longer a good choice. Yes, it's caching but for large data and distributed scenarios. In addition, you have to install additional dedicated servers for the caching tier.

Maybe a basic MemoryCache is enough to start : Local Cache, Nothing to install, no additional servers required and built-in support in .net bcl.

Here is a basic example :

//Create a cache instance
ObjectCache cache = MemoryCache.Default;     

//check the cache for a specific value
if (cache.Contains("mydata"))     
{         
    //get an item from the cache
    var value=cache.Get("mydata");     
}     
else    
{     
    //load data
    var data=fetchData();
    //add an data to the cache 
    cache.Add("mydata", data);     
} 

For caching a small piece of data and for one (or a few) web servers, it's fairly enough.