nopCommerce 数据缓存

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

一、Nop.Core.Caching.ICacheManager

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

  1. namespace Nop.Core.Caching
    {
    /// <summary>
    /// Cache manager interface
    /// </summary>
    public interface ICacheManager
    {
    /// <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>(string 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>
    void Set(string key, object data, int cacheTime);
    /// <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(string key);
    /// <summary>
    /// Removes the value with the specified key from the cache
    /// </summary>
    /// <param name="key">/key</param>
    void Remove(string key);
    /// <summary>
    /// Removes items by pattern
    /// </summary>
    /// <param name="pattern">pattern</param>
    void RemoveByPattern(string pattern);
    /// <summary>
    /// Clear all cache data
    /// </summary>
    void Clear();
    }
    }
    二、Nop.Core.Caching.MemoryCacheManager
    
    接口ICacheManager具体实现是在类Nop.Core.Caching.MemoryCacheManager:
    
    using System;
    using System.Collections.Generic;
    using System.Runtime.Caching;
    using System.Text.RegularExpressions;
    namespace Nop.Core.Caching
    {
    /// <summary>
    /// Represents a manager for caching between HTTP requests (long term caching)
    /// </summary>
    public partial class MemoryCacheManager : ICacheManager
    {
    protected ObjectCache Cache
    {
    get
    {
    return MemoryCache.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>(string key)
    {
    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, int cacheTime)
    {
    if (data == null)
    return;
    var policy = new CacheItemPolicy();
    policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
    Cache.Add(new CacheItem(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(string key)
    {
    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(string key)
    {
    Cache.Remove(key);
    }
    /// <summary>
    /// Removes items by pattern
    /// </summary>
    /// <param name="pattern">pattern</param>
    public virtual void RemoveByPattern(string pattern)
    {
    var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
    var keysToRemove = new List<String>();
    foreach (var item in Cache)
    if (regex.IsMatch(item.Key))
    keysToRemove.Add(item.Key);
    foreach (string key in keysToRemove)
    {
    Remove(key);
    }
    }
    /// <summary>
    /// Clear all cache data
    /// </summary>
    public virtual void Clear()
    {
    foreach (var item in Cache)
    Remove(item.Key);
    }
    }
    }

     

 

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

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

 

  1. using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    using System.Web;
    namespace Nop.Core.Caching
    {
    /// <summary>
    /// Represents a manager for caching during an HTTP request (short term caching)
    /// </summary>
    public partial class PerRequestCacheManager : ICacheManager
    {
    private readonly HttpContextBase _context;
    /// <summary>
    /// Ctor
    /// </summary>
    /// <param name="context">Context</param>
    public PerRequestCacheManager(HttpContextBase context)
    {
    this._context = context;
    }
    /// <summary>
    /// Creates a new instance of the NopRequestCache class
    /// </summary>
    protected virtual IDictionary 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]
    public ActionResult 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 = new BlogPostTagListModel();
    //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 in tags)
    model.Tags.Add(new BlogPostTagModel()
    {
    Name = tag.Name,
    BlogPostCount = tag.BlogPostCount
    });
    return model;
    });
    return PartialView(cachedModel);
    }

     

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

  1. using System;
    namespace Nop.Core.Caching
    {
    /// <summary>
    /// Extensions
    /// </summary>
    public static class CacheExtensions
    {
    /// <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);
    return result;
    }
    }
    }
    }

     

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

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

 

转载于:https://www.cnblogs.com/xchit/p/5085740.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: nopCommerce是一种免费开源的电子商务解决方案,可以用于创建和管理在线商店。它具有高度灵活性和可扩展性,适用于各种规模和类型的企业。对于没有技术背景或经验的商家来说,nopCommerce提供了托管解决方案,使他们可以轻松搭建和管理自己的在线商店。 通过nopCommerce托管,商家无需关心服务器设置和管理等技术问题。托管方会提供服务器基础设施、数据库和通信连接等,以确保商店的正常运行和安全性。商家只需要关注商店的内容和产品,并使用nopCommerce的商家后台管理工具进行设置和配置。 托管解决方案还提供了多种商店模板和主题,商家可以根据自己的品牌形象和需求选择合适的外观和布局。此外,托管方还会提供备份和数据恢复等服务,以防止数据丢失和不可预见的故障。 对于一些规模较小的企业或个人商家来说,选择nopCommerce托管可以节省时间和成本,因为他们无需进行服务器配置和维护。同时,nopCommerce托管方会提供技术支持和更新服务,以确保商店始终保持最新和安全的状态。 总之,nopCommerce托管为商家提供了一个简单和方便的方式来创建和管理自己的在线商店。商家可以专注于业务发展,而不必花费过多的时间和精力在技术细节上。无论是初创企业还是规模较大的公司,nopCommerce托管都提供了一个强大和可靠的电子商务解决方案。 ### 回答2: nopCommerce是一个开源的电子商务平台,可以通过托管的方式进行部署和运行。托管意味着将整个nopCommerce网站部署在一个托管服务提供商的服务器上,而不需要自己搭建和维护服务器。 选择nopCommerce托管的好处之一是省去了自行购买服务器的成本和用户维护服务器的繁琐工作。托管服务提供商通常会提供稳定的服务器基础设施和网络连接,以确保网站的稳定运行和可靠性。用户只需根据自己的需求选择一个可靠的托管服务提供商,并与其合作购买托管服务,即可将nopCommerce网站部署在托管服务提供商的服务器上。 另一个好处是托管服务商通常会提供备份和恢复的功能,以确保网站数据的安全性。它们会定期备份网站数据,并在需要的时候进行恢复。用户不需要担心数据丢失或损坏的问题,因为托管服务商会负责备份和恢复。 此外,对于不具备服务器管理经验或技术知识的用户来说,托管是一个更好的选择。托管服务提供商会负责服务器的日常维护和管理工作,包括服务器更新、安全补丁和性能优化等。用户只需要关注网站的内容和业务,而不必花费精力去学习和处理服务器管理问题。 当然,与托管服务相关的费用是需要考虑的因素之一。托管服务通常需要付费,其费用取决于所选择的托管服务提供商及其提供的服务级别。用户需要根据自己的预算和需求选择适合的托管服务。 总结起来,nopCommerce托管是一种方便、省力且可靠的选择。它提供了稳定的服务器基础设施、备份和恢复功能,并减轻了用户的服务器管理负担。当然,用户需要根据自己的需求和预算选择合适的托管服务提供商。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值