首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >泛型MemoryCache类

泛型MemoryCache类
EN

Code Review用户
提问于 2014-03-01 02:08:32
回答 2查看 3.2K关注 0票数 4

我希望有一个缓存类来缓存不同的类型。我希望每种类型都在不同的MemoryCache中缓存,但要以一种通用的方式缓存。

我做得对吗?

代码语言:javascript
复制
internal static class RecordsCache
{
    private static Dictionary<string, ObjectCache> cacheStore;
    static private CacheItemPolicy policy = null;

    static RecordsCache()
    {
        cacheStore = new Dictionary<string, ObjectCache>();

        ObjectCache activitiesCache = new MemoryCache(typeof(Activity).ToString());
        ObjectCache lettersCache = new MemoryCache(typeof(Letter).ToString());
        ObjectCache contactssCache = new MemoryCache(typeof(Contact).ToString());

        cacheStore.Add(typeof(Activity).ToString(), activitiesCache);
        cacheStore.Add(typeof(Letter).ToString(), lettersCache );
        cacheStore.Add(typeof(Contact).ToString(), contactssCache );

        policy = new CacheItemPolicy();
        policy.Priority = CacheItemPriority.Default;
        policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(12);
    }

    public static void Set<T>(string userID, int year, List<T> records)
    {
        var cache = cacheStore[typeof(T).ToString()];
        string key = userID + "-" + year.ToString();
        cache.Set(key, records, policy);
    }

    public static bool TryGet<T>(string userID, int year, out List<T> records)
    {
        var cache = cacheStore[typeof(T).ToString()];
        string key = userID + "-" + year.ToString();

        records = cache[key] as List<T>;
        return records != null;
    }

    public static void Remove<T>(string userID, int year)
    {
        var cache = cacheStore[typeof(T).ToString()];
        string key = userID + "-" + year.ToString();
        cache.Remove(key);
    }
}
EN

回答 2

Code Review用户

回答已采纳

发布于 2014-03-01 08:01:26

  1. 而不是拥有一个缓存私有静态Dictionary cacheStore;您可以有一个键类型:私有静态Dictionary cacheStore;这意味着您不需要到处调用typeof(T).ToString()
  2. 您复制了在所有三个方法中构建密钥的代码--应该将其提取到私有的BuildKey(string userId, int year)方法中。这意味着,如果您需要更改键的构建方式,您只需要触摸一个方法,而不是所有的方法。
  3. 我将提供一个Register方法,它接受要为其创建新缓存的类型,而不是硬编码它。
  4. 缓存策略也是不可配置的--这意味着除非您想要更改代码,否则您将继续使用它。
  5. 您真的应该认真考虑静态缓存是否是正确的方法。它将在单元测试中给您带来麻烦,也会使多个类不可能有不同的缓存,例如,不同的策略。
票数 7
EN

Code Review用户

发布于 2014-03-01 07:28:08

在我看来,每件事都有很好的编码。

这里只是一些个人偏好:

  1. 我将提供另外一个Set<T>方法,它接受一个函数作为输入,而不是List<T>:公共静态空集(string userId,int,Func> retrieveData) {}
  2. 我希望有更多一种方法将GetSet组合在一起,看起来是: public List TryGetAndSet(string userId,int retrieveData,Func> retrieveData) { //如果缓存项存在返回cacheItem //如果缓存项不存在,则通过执行retrieveData//如果检索到的结果,设置为缓存并返回结果}来检索数据。
  3. 多1项,以检查某些缓存项是否存在。
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/43111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档