0

我想设计一种自动化的方式来保存/检索来自cache. 这就是我想为它设计架构的方式。

将有2个类库

DB.DataAccess -> 该层将使用 ado.net 执行 sp/quires 以访问数据库中的数据

DB.DataDistributor -> 这将是 db 和表示层之间的中间层,调用 DB.DataAccess 来获取数据

在 DB.DataDistributor 中,我想通过使用自定义属性以这种方式自动化数据缓存。

namespace DB.DataDistributor
{
    public class MessageManager
    {


        [CachDataAttribute(CacheKey = CacheKeys.Message, CacheDataType = typeof(List<Message>))]
        public List<Message> GetMessages()
        {
            DB.DataAccess.MesssageManager msgManager = null;
            try
            {
                msgManager = new DB.DataAccess.MesssageManager();
                var messages = msgManager.GetMessages();
                return messages;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                msgManager = null;
            }
        }


    }
}

namespace DB.DataDistributor
{
    [AttributeUsage(AttributeTargets.Method)]
    internal class DataCachingFilterAttribute : Attribute
    {
        public CacheKeys CacheKey { get; set; }
        public Type CacheDataType { get; set; }

        public void SetCache()
        {
            //this method should call after execution of method where DataCachingFilterAttribute has attached 
        }

        public void GetCache()
        {
            //this method should call before execution of method where DataCachingFilterAttribute has attached
            //here I will check if data available in cache then will return data from cache and do not call the achtual method 
        }
    }

    public enum CacheKeys
    {
        Message
    }
}
  • 每当表示层调用系统的 GetMessages方法 时,如果在缓存中找到数据,则不应执行实际方法,并且数据直接从缓存返回,否则调用并从那里返回数据。DB.DataDistributor.MessageManagerGetCache()DataCachingFilterAttributeGetMessagesGetMessages

  • GetMessages在从应该调用的SetCache方法 返回结果后DataCachingFilterAttribute立即将结果设置在缓存中。

这是我自动化数据缓存的想法,但我不知道如何在方法执行DataCachingFilterAttribute之前和之后触发方法GetMessages

如果有人有任何想法或其他好的方法来自动化缓存,请分享。

4

0 回答 0