0

I'm new to the concept of caching data and I wanted to ask if there are any issues I"m overlooking with the strategy I"m building for caching data in my MVC web application from my database. I want to stress that basically the data I'm looking at caching is practically read only, and would only be updated very very infrequently (coinciding with code upgrades where the app would be being refreshed).

From what I have been able to research I was planning on using a static class to serve as a helper for building and maintaining the cache. The below code shows how I would build the cache from a database table which would contain the different baseball card condition grades (Mint, Near Mint, etc)

Static CacheHelper class:

public static class CacheHelpers
{
    private static HashSet<baseballcardcondition> _CardConditionsCache = null;
    public static HashSet<baseballcardcondition> CardConditionsCache
    {
        get
        {
            if (_CardConditionsCache == null)
            {
                _CardConditionsCache = (HttpContext.Current.Cache["CardConditionsCache"] as HashSet<baseballcardconditions>);
                if (_CardConditionsCache == null)
                {
                    mydbEntities db = new mydbEntities();
                    _CardConditionsCache = new HashSet<baseballcardconditions>(db.baseballcardconditions);
                    HttpContext.Current.Cache.Insert("CardConditionsCache", _CardConditionsCache);
                }
            }
            return _CardConditionsCache;
        }
        set
        {
            HttpContext.Current.Cache.Insert("CardConditionsCache", _CardConditionsCache);
        }
    }//public static HashSet<baseballcardconditions> CardConditionsCache
}//public static class CacheHelpers

Later I would be using this data to build a formatted string for a jqGrid grid (a jQuery javascript plugin for displaying tabular data) and would access it via:

        //cardConditionSelectListHelperString
        string tempString = "";

        foreach (var keyPair in CacheHelpers.CardConditionsCache)
        {
            tempString += keyPair.IdBaseballCardCondition + ":" + keyPair.Condition + ";";
        }

Does this look like a solid, robust, and thread safe way to manage my cache for my MVC web application? I would probably expand my CacheHelpers class to have other cached Hashsets so I don't have to hit the database for this read only, basically static data.

Thank you in advance.

4

1 回答 1

0

“这看起来像是一种可靠、健壮且线程安全的方式来管理我的 MVC Web 应用程序的缓存吗?”

不,它没有。例如,您如何保持较小的数据大小?您应该从缓存中刷新未使用的数据(检查:http: //msdn.microsoft.com/en-us/library/dd632018.aspx)。此外,它不是线程安全的。

我认为创建自己的缓存解决方案是典型的“重新邀请轮子”场景,市场上有很多缓存(甚至是分布式缓存) - 此外其中一些是免费的。一个好的缓存解决方案比刚开始使用一些静态字段要复杂得多。

于 2013-04-03T15:10:24.860 回答