缓存数据库查询的最佳方法是什么

时间:2013-07-05 08:50:06

标签: c# entity-framework design-patterns caching

我正在编写一个管理智能应用程序,它需要进行大量复杂的数据库查询,而某些查询非常昂贵。为了提高性能,我正在大量使用Memcached来尽可能多地存储在内存中。

这导致我的代码中出现了很多重复,我急于摆脱并构建更清晰的数据访问解决方案。我的很多数据访问功能看起来都像这样......

public int NumberOfTimeouts(DateTime date, int? applicationId)
{
    var functionCacheKey = "NumberOfTimeouts";
    var cacheKey = string.Format("{0}-{1}-{2}-{3}", RepositoryCacheKey, functionCacheKey, date, applicationId);
    var cachedNumberTimeouts = _cache.Retrieve(cacheKey);
    if (cachedNumberTimeouts != null)
    {
        return (int)cachedNumberTimeouts;
    }

    //query logic here, calculates numberOfTimeouts

    UpdateCache(date, cacheKey, numberOfTimeouts);
    return numberOfTimeouts;
}

我只是不太清楚标准方法是什么,它是否涉及使用自定义属性类或类似的东西?

2 个答案:

答案 0 :(得分:1)

这是一个贯穿各领域的问题。 Decorator模式可能适用于此处。我可能对这种模式缺乏经验,但我会试一试

// model
public class CustomObject
{
    public int Id { get; set; }
}
// interface
public interface IRepository<T>
{
    IEnumerable<T> Find(Expression<Func<T, bool>> expression);
}
public interface ICacheableRepository<T>
{
    IEnumerable<T> Find(Expression<Func<T, bool>> expression, Func<int> cacheKey);
}
public interface IRepositoryCacheManager<T>
{
    IEnumerable<T> Get(int key);
    bool Any(int key);
    void Add(int key, IEnumerable<T> result);
}
// cache manager
public class RepositoryCacheManager<T> : IRepositoryCacheManager<T>
{
    private Dictionary<int, IEnumerable<T>> cache = new Dictionary<int,IEnumerable<T>>();
    #region IRepositoryCache<T> Members

    public IEnumerable<T> Get(int key)
    {
        return cache[key];
    }

    public bool Any(int key)
    {
        IEnumerable<T> result = null;
        return cache.TryGetValue(key, out result);
    }

    public void Add(int key, IEnumerable<T> result)
    {
        cache.Add(key, result);
    }

    #endregion
}

// cache repository decorator
public class CachedRepositoryDecorator<T> : IRepository<T>, ICacheableRepository<T>
{
    public CachedRepositoryDecorator(IRepositoryCacheManager<T> cache
        , IRepository<T> member)
    {
        this.member = member;
        this.cache = cache;
    }

    private IRepository<T> member;
    private IRepositoryCacheManager<T> cache;

    #region IRepository<T> Members

    // this is not caching
    public IEnumerable<T> Find(Expression<Func<T, bool>> expression)
    {
        return member.Find(expression);
    }

    #endregion

    #region ICacheableRepository<T> Members

    public IEnumerable<T> Find(Expression<Func<T, bool>> expression, Func<int> cacheKey)
    {
        if (cache.Any(cacheKey()))
        {
            return cache.Get(cacheKey());
        }
        else
        {
            IEnumerable<T> result = member.Find(expression);
            cache.Add(cacheKey(), result);
            return result;
        }
    }

    #endregion
}
// object repository
public class CustomObjectRepository : IRepository<CustomObject>
{
    #region IRepository<CustomObject> Members

    public IEnumerable<CustomObject> Find(Expression<Func<CustomObject, bool>> expression)
    {
        List<CustomObject> cust = new List<CustomObject>();
        // retrieve data here
        return cust;
    }

    #endregion
}
// example
public class Consumer
{
    // this cache manager should be persistent, maybe can be used in static, etc
    IRepositoryCacheManager<CustomObject> cache = new RepositoryCacheManager<CustomObject>();
    public Consumer()
    {
        int id = 25;

        ICacheableRepository<CustomObject> customObjectRepository =
            new CachedRepositoryDecorator<CustomObject>(
                cache
                , new CustomObjectRepository()
                );
        customObjectRepository.Find(k => k.Id == id, () => { return id; });
    }
}

请注意:

  • 我没有测试过这段代码,也不知道它是否完全正常运行。我只是描述插图
  • 是的,ICacheableRepository的{​​{1}}重载会产生代码异味,但我无法在Find中使用Expression作为Key

专业人士:

  • 此CachedRepositoryDe​​corator可用于任何通用存储库(可重用)
  • 选择过程中没有缓存逻辑,强调Dictionary

缺点:

  • 如果没有ORM,很难实现,也许你需要进行一些反思调整才能让它在没有ORM的情况下工作
  • 开头很难理解
  • 没有DI容器时难以接线

相信这个article:)

答案 1 :(得分:0)