开发者

MVC 2 - Caching Strings in Memory

I would like to cache strings in memory from the database so that I do not have to access the databas开发者_运维百科e every time. I tried using System.Runtime.Caching, but it does not seem to work.

On the local site, all the data is cached but the user has to be authenticated on a secondary site. Once the user is authenticated, they are brought back to the local site but all the data that was cached is gone.

Is there a way to fix the above issue? Below is part of my code:

using System.Runtime.Caching;

ObjectCache cache = MemoryCache.Default;

public bool CacheIsSet(string key)
{
    return cache.Contains(key);
}

public object CacheGet(string key)
{
    return cache.Get(key);
}

public void CacheSet(string key, object value)
{
    CacheItemPolicy policy = new CacheItemPolicy();
    cache.Set(key, value, policy);
}

Thanks very much.


You should be referencing the HttpRuntime.Cache object. I created a wrapper around this, similar to what you have referenced in your question. Feel free to use it:

using System.Web.Caching;

public class CachingService
{
     protected Cache Cache
     {
         get;
         set;
     }

     public int CacheDurationMinutes
     {
         get;
         set;
     }

     public CachingService()
     {
         Cache = HttpRuntime.Cache;
         CacheDurationMinutes = 60;
     }

     public virtual object Get(string keyname)
     {
         return Cache[keyname];
     }

     public virtual T Get<T>(string keyname)
     {
         T item = (T)Cache[keyname];

         return item;
     }

     public virtual void Insert(string keyname, object item)
     {
         Cache.Insert(keyname, item, null, DateTime.UtcNow.AddMinutes(CacheDurationMinutes), Cache.NoSlidingExpiration);
     }

     public virtual void Insert(string keyname, object item, CacheDependency dependency)
     {
         Cache.Insert(keyname, item, dependency);
     }

     public virtual void Remove(string keyname)
     {
         Cache.Remove(keyname);
     }
}

Here is a sample use case. The function LoadPosts is supposed to load blog posts to display on the site. The function will first see if the posts are cached, if not it will load the posts from the database, and then cache them:

public IEnumerable<BlogPost> LoadPosts() 
{
  var cacheService = new CachingService();
  var blogPosts = cacheService.Get<IEnumerable<BlogPost>>("BlogPosts");

  if (blogPosts == null)
  {
     blogPosts = postManager.LoadPostsFromDatabase();
     cacheService.Insert("BlogPosts", blogPosts);
  }

  return blogPosts;
}

The first time this function is run, the cache will return null, because we didn't add anything to the BlogPosts key yet. The second time the function is called the posts will be in the cache and the code in the if block will not run, saving us a trip to the database.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜