nopCommerce 数据缓存

摘要:
为了提高一个系统或网站的性能和IO吞吐量,我们一般都会采用缓存技术。当然NopCommerce也不例外,本文我们就来给大家分析一下nop中Cache缓存相关类设计、核心源码及实现原理。

为了提高一个系统或网站的性能和IO吞吐量,我们一般都会采用缓存技术。当然NopCommerce也不例外,本文我们就来给大家分析一下nop中Cache缓存相关类设计、核心源码及实现原理。

一、Nop.Core.Caching.ICacheManager

Nop首先抽象出了一个缓存存储和读取相关管理接口Nop.Core.Caching.ICacheManager。

  1. namespaceNop.Core.Caching
    {
    /// <summary>
    ///Cache manager interface
    /// </summary>
    public interfaceICacheManager
    {
    /// <summary>
    ///Gets or sets the value associated with the specified key.
    /// </summary>
    /// <typeparam name="T">Type</typeparam>
    /// <param name="key">The key of the value to get.</param>
    /// <returns>The value associated with the specified key.</returns>
    T Get<T>(stringkey);
    /// <summary>
    ///Adds the specified key and object to the cache.
    /// </summary>
    /// <param name="key">key</param>
    /// <param name="data">Data</param>
    /// <param name="cacheTime">Cache time</param>
    void Set(string key, object data, intcacheTime);
    /// <summary>
    ///Gets a value indicating whether the value associated with the specified key is cached
    /// </summary>
    /// <param name="key">key</param>
    /// <returns>Result</returns>
    bool IsSet(stringkey);
    /// <summary>
    ///Removes the value with the specified key from the cache
    /// </summary>
    /// <param name="key">/key</param>
    void Remove(stringkey);
    /// <summary>
    ///Removes items by pattern
    /// </summary>
    /// <param name="pattern">pattern</param>
    void RemoveByPattern(stringpattern);
    /// <summary>
    ///Clear all cache data
    /// </summary>
    voidClear();
    }
    }
    二、Nop.Core.Caching.MemoryCacheManager
    
    接口ICacheManager具体实现是在类Nop.Core.Caching.MemoryCacheManager:
    
    usingSystem;
    usingSystem.Collections.Generic;
    usingSystem.Runtime.Caching;
    usingSystem.Text.RegularExpressions;
    namespaceNop.Core.Caching
    {
    /// <summary>
    ///Represents a manager for caching between HTTP requests (long term caching)
    /// </summary>
    public partial classMemoryCacheManager : ICacheManager
    {
    protectedObjectCache Cache
    {
    get{
    returnMemoryCache.Default;
    }
    }
    /// <summary>
    ///Gets or sets the value associated with the specified key.
    /// </summary>
    /// <typeparam name="T">Type</typeparam>
    /// <param name="key">The key of the value to get.</param>
    /// <returns>The value associated with the specified key.</returns>
    public virtual T Get<T>(stringkey)
    {
    return(T)Cache[key];
    }
    /// <summary>
    ///Adds the specified key and object to the cache.
    /// </summary>
    /// <param name="key">key</param>
    /// <param name="data">Data</param>
    /// <param name="cacheTime">Cache time</param>
    public virtual void Set(string key, object data, intcacheTime)
    {
    if (data == null)
    return;
    var policy = newCacheItemPolicy();
    policy.AbsoluteExpiration = DateTime.Now +TimeSpan.FromMinutes(cacheTime);
    Cache.Add(newCacheItem(key, data), policy);
    }
    /// <summary>
    ///Gets a value indicating whether the value associated with the specified key is cached
    /// </summary>
    /// <param name="key">key</param>
    /// <returns>Result</returns>
    public virtual bool IsSet(stringkey)
    {
    return(Cache.Contains(key));
    }
    /// <summary>
    ///Removes the value with the specified key from the cache
    /// </summary>
    /// <param name="key">/key</param>
    public virtual void Remove(stringkey)
    {
    Cache.Remove(key);
    }
    /// <summary>
    ///Removes items by pattern
    /// </summary>
    /// <param name="pattern">pattern</param>
    public virtual void RemoveByPattern(stringpattern)
    {
    var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled |RegexOptions.IgnoreCase);
    var keysToRemove = new List<String>();
    foreach (var item inCache)
    if(regex.IsMatch(item.Key))
    keysToRemove.Add(item.Key);
    foreach (string key inkeysToRemove)
    {
    Remove(key);
    }
    }
    /// <summary>
    ///Clear all cache data
    /// </summary>
    public virtual voidClear()
    {
    foreach (var item inCache)
    Remove(item.Key);
    }
    }
    }

可以看到上面Nop的缓存数据是使用的的MemoryCache.Default来存储的,MemoryCache.Default是获取对默认 System.Runtime.Caching.MemoryCache 实例的引用,缓存的默认实例,也就是程序运行的内存中。

Nop除了提供了一个MemoryCacheManager,还有一个Nop.Core.Caching.PerRequestCacheManager类,它提供的是MemoryCacheManager相同的功能,不过它是把数据存在HttpContextBase.Items中,如下:

  1. usingSystem;
    usingSystem.Collections;
    usingSystem.Collections.Generic;
    usingSystem.Text.RegularExpressions;
    usingSystem.Web;
    namespaceNop.Core.Caching
    {
    /// <summary>
    ///Represents a manager for caching during an HTTP request (short term caching)
    /// </summary>
    public partial classPerRequestCacheManager : ICacheManager
    {
    private readonlyHttpContextBase _context;
    /// <summary>
    ///Ctor
    /// </summary>
    /// <param name="context">Context</param>
    publicPerRequestCacheManager(HttpContextBase context)
    {
    this._context =context;
    }
    /// <summary>
    ///Creates a new instance of the NopRequestCache class
    /// </summary>
    protected virtualIDictionary GetItems()
    {
    if (_context != null)
    return_context.Items;
    return null;
    }
    //省略其它代码....
    }
    }

三、缓存接口ICacheManager依赖注入

缓存接口ICacheManager使用了依赖注入,我们在Nop.Web.Framework.DependencyRegistrar类中就能找到对ICacheManager的注册代码:

  1. //cache manager
    builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();
    builder.RegisterType<PerRequestCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_per_request").InstancePerLifetimeScope();
    //pass MemoryCacheManager as cacheManager (cache settings between requests)
    builder.RegisterType<ProductTagService>().As<IProductTagService>()
    .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
    .InstancePerLifetimeScope();
    //pass MemoryCacheManager as cacheManager (cache settings between requests)
    builder.RegisterType<PermissionService>().As<IPermissionService>()
    .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
    .InstancePerLifetimeScope();
    //pass MemoryCacheManager as cacheManager (cache settings between requests)
    builder.RegisterType<AclService>().As<IAclService>()
    .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
    .InstancePerLifetimeScope();
    //pass MemoryCacheManager as cacheManager (cache settings between requests)
    builder.RegisterType<PriceCalculationService>().As<IPriceCalculationService>()
    .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
    .InstancePerLifetimeScope();
    //pass MemoryCacheManager as cacheManager (cache settings between requests)
    builder.RegisterType<CustomerActivityService>().As<ICustomerActivityService>()
    .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
    .InstancePerLifetimeScope();

上面最开始对接口ICacheManager两实现分别是MemoryCacheManager和PerRequestCacheManager并通过.Named来区分。Autofac高级特性--注册Named命名和Key Service服务

接下来可以配置不同的Service依赖不同的ICacheManager的实现:.WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))或者.WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_per_request"))。

四、具体实例BlogController

下面我们来举例看一下怎么使用这个缓存的。我们就以Nop.Web.Controllers.BlogController的方法BlogTags为例:

  1. [ChildActionOnly]
    publicActionResult BlogTags()
    {
    if (!_blogSettings.Enabled)
    return Content("");
    var cacheKey = string.Format(ModelCacheEventConsumer.BLOG_TAGS_MODEL_KEY, _workContext.WorkingLanguage.Id, _storeContext.CurrentStore.Id);
    var cachedModel = _cacheManager.Get(cacheKey, () =>{
    var model = newBlogPostTagListModel();
    //get tags
    var tags =_blogService.GetAllBlogPostTags(_storeContext.CurrentStore.Id, _workContext.WorkingLanguage.Id)
    .OrderByDescending(x =>x.BlogPostCount)
    .Take(_blogSettings.NumberOfTags)
    .ToList();
    //sorting
    tags = tags.OrderBy(x =>x.Name).ToList();
    foreach (var tag intags)
    model.Tags.Add(newBlogPostTagModel()
    {
    Name =tag.Name,
    BlogPostCount =tag.BlogPostCount
    });
    returnmodel;
    });
    returnPartialView(cachedModel);
    }

上面var cachedModel = _cacheManager.Get就是从缓存中读取数据,_cacheManager的Get方法第二个参数是一个lambda表达式,可以传一个方法,这时我们就可以把数据的从数据库中的逻辑放在里面,注意:当第二次请求数据时,如果缓存中有数据,这个Lambda方法是不会执行的。为什么呢?我们可以选中_cacheManager的Get方法按F12进去看这个方法的实现就知道了:

  1. usingSystem;
    namespaceNop.Core.Caching
    {
    /// <summary>
    ///Extensions
    /// </summary>
    public static classCacheExtensions
    {
    /// <summary>
    ///Get a cached item. If it's not in the cache yet, then load and cache it
    /// </summary>
    /// <typeparam name="T">Type</typeparam>
    /// <param name="cacheManager">Cache manager</param>
    /// <param name="key">Cache key</param>
    /// <param name="acquire">Function to load item if it's not in the cache yet</param>
    /// <returns>Cached item</returns>
    public static T Get<T>(this ICacheManager cacheManager, string key, Func<T>acquire)
    {
    return Get(cacheManager, key, 60, acquire);
    }
    /// <summary>
    ///Get a cached item. If it's not in the cache yet, then load and cache it
    /// </summary>
    /// <typeparam name="T">Type</typeparam>
    /// <param name="cacheManager">Cache manager</param>
    /// <param name="key">Cache key</param>
    /// <param name="cacheTime">Cache time in minutes (0 - do not cache)</param>
    /// <param name="acquire">Function to load item if it's not in the cache yet</param>
    /// <returns>Cached item</returns>
    public static T Get<T>(this ICacheManager cacheManager, string key, int cacheTime, Func<T>acquire)
    {
    if(cacheManager.IsSet(key))
    {
    return cacheManager.Get<T>(key);
    }
    else{
    var result =acquire();
    if (cacheTime > 0)
    cacheManager.Set(key, result, cacheTime);
    returnresult;
    }
    }
    }
    }

可以看到其实上面_cacheManager.Get调用的是类型ICacheManager的一个扩展方法。第二个方法就可以知道,当缓存中有数据直接返回cacheManager.Get<T>(key),如果没有才进入else分支,执行参数的Lambda表达方式acquire()。

博客园的这篇文章写的不错:http://www.cnblogs.com/gusixing/archive/2012/04/12/2443799.html

免责声明:文章转载自《nopCommerce 数据缓存》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Memcache数据备份和还原STL中的查找下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

k8s集群上删除pod及service

删除k8s集群中的pod:找到pod的名称空间,并根据名称空间删除pod1。首先删除pod2,然后删除相应的部署。否则,删除pod是无用的。您还将看到pod,因为deployment.yaml文件中定义的副本数如下:delete the pod[root@test2~]#kubectlgetpod-njenkinsNAMEREADYSTATUSRESTART...

"SQLserver 事务日志已满"解决方法

如果不够,备份后换个地方存[注:tempdb你数据库名称。...

10 TCP限流技术

TCP流限制的原因是接收方可以完全接受消息,以确保数据安全而不会丢失。首先,窗口机制引入了发送方和接收方都有一个窗口。当发送方发送数据时,将发送落入窗口中的数据。当接收器接收到数据时,落入接收器窗口的数据将被接受。可以看出,流量会受到窗口大小II的限制。滑动窗口技术1TCP滑动窗口技术通过动态改变窗口大小来调整两台主机之间的数据传输。...

winform中 跨线程启动UI

C#的winform程序中,是不可以从UI窗口主线程之外的线程去直接操作窗口控件的。确切的解释是,不能从创建控件的线程以外的线程去处理控件的操作,比如修改属性等。方法二,通过Control.Invoke调用委托的方式来执行。...

【01】如何在XMind中排列自由主题

如何在XMind中安排免费主题。在XMind思维导图软件中,用户可以根据需要添加免费主题。然而,由于自由主题的灵活性,它并不整洁,与需要控制界面有序排列的用户相比,这会造成一定的麻烦。首先选择要组织的所有免费主题,单击,然后在下拉框中选择以安排免费主题。有六种排列方式:左对齐、垂直居中、右对齐、顶部对齐、水平居中和底部对齐。...

matlab从曲线图提取数据

对于第二条曲线,add_len需要改小,欧式距离的阈值需要改大。...