开发者

ASP.Net | Caching items in a hashtable or individual items | Needs suggestion

开发者 https://www.devze.com 2023-04-06 21:31 出处:网络
I have a WCF service say- Service A, which returns the name of a person based on his personId. Retrieving the person\'s name from PersonId is actually served by another Service say -B.

I have a WCF service say- Service A, which returns the name of a person based on his personId. Retrieving the person's name from PersonId is actually served by another Service say -B.

So Service A pass person Id to Service B which returns Person Name.

Now i want that Service A should call Service B only if Service B has not been called for a personId.

So i want to implement Caching as follows:

Cache the personid ,Person Name combination once we have retrieved it from Service B. Also I want to put a time based dependancy on the individual item. If an individual personId item has not been access since 1 hour it should expire.

Now I have two approaches

A) Create a hashTable of personid and personName . Everytime there is a request for a PersonID first check if the personId exists in the Hash .If it does -then serve it from the Cache else call Service B. If it does-not Call service B. Add the person ID person Name combination to the Hashtable and then put this HashTable into the Cache.

Problem: How do i put a dependency on an individual item. Putting a dependency on the HashTable will not solve this

B) Cache Individual Personid and PersonName. Everytime there is a开发者_运维百科 request check if the PersonId exists in the Cache. If yes serve it from Cache if not Call Service B.

Problem: This will introduce a lot of items in the Cache. Will this create any issue ?

Which approach should i go for and how?


What kind of cache framework are you going to use? Have a look at System.Runtime.Caching from .NET 4 - it should solve your dilemma. For example, you can use a different cache bag for caching persons:

private static ObjectCache personCache = new MemoryCache();

private Person Get(string id)
{
   var p = personCache[id] as Person;
   if (null == p)
   {
        // Make the service call to get the person
        ...
        // add to cache
        personCache.Add(id, p, DateTime.Now.AddMinutes(30));
   }
   return p;
}

For prior .NET versions, you can use Caching Application Block.

0

精彩评论

暂无评论...
验证码 换一张
取 消