我的NopCommerce之旅(5): 缓存

一、基础介绍

1.什么是cache
     Web缓存是指一个Web资源(如html页面,图片,js,数据等)存在于Web服务器和客户端(浏览器)之间的副本。
2.为什么要用cache
     即cache的作用,有以下几点:
     2.1.减少网络带宽消耗;
     2.2.降低服务器压力;
     2.3.减少网络延迟、加快页面打开速度。
3.cache的分类
     常见分类如下:
     3.1.数据库数据缓存;
     3.2.服务器端缓存;
          a.代理服务器缓存
          b.CDN缓存
     3.3.浏览器缓存;
     3.4.Web应用缓存

二、NopCommerce的缓存分析

1.UML
     接口ICacheManager;
     实现MemoryCacheManager(HTTP请求缓存,生命周期长),NopNullCache(仅实现接口,不提供缓存机制),PerRequestCacheManager(HTTP请求缓存,生命周期短),RedisCacheManager(Redis缓存);
     扩展CacheExtensions;
2.代码分析
     2.1.Nop.Web.Framework.DependencyRegistrar类,配置依赖注入的ICacheManager。
     
1             //cache managers
2             if (config.RedisCachingEnabled)
3             {
4                 builder.RegisterType<RedisCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").InstancePerLifetimeScope();
5             }
6             else
7             {
8                 builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();
9             }

     2.2.RedisCachingEnabled通过读取配置文件,见Nop.Core.Configuration.NopConfig

     
 1             var redisCachingNode = section.SelectSingleNode("RedisCaching");
 2             if (redisCachingNode != null && redisCachingNode.Attributes != null)
 3             {
 4                 var enabledAttribute = redisCachingNode.Attributes["Enabled"];
 5                 if (enabledAttribute != null)
 6                     config.RedisCachingEnabled = Convert.ToBoolean(enabledAttribute.Value);
 7 
 8                 var connectionStringAttribute = redisCachingNode.Attributes["ConnectionString"];
 9                 if (connectionStringAttribute != null)
10                     config.RedisCachingConnectionString = connectionStringAttribute.Value;
11             }

3.应用

     通过依赖注入,生成缓存管理类实例,通过方法读取、设置缓存。
     
        [NonAction]
        protected virtual List<int> GetChildCategoryIds(int parentCategoryId)
        {
            string cacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_CHILD_IDENTIFIERS_MODEL_KEY, 
                parentCategoryId, 
                string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()), 
                _storeContext.CurrentStore.Id);
            return _cacheManager.Get(cacheKey, () =>
            {
                var categoriesIds = new List<int>();
                var categories = _categoryService.GetAllCategoriesByParentCategoryId(parentCategoryId);
                foreach (var category in categories)
                {
                    categoriesIds.Add(category.Id);
                    categoriesIds.AddRange(GetChildCategoryIds(category.Id));
                }
                return categoriesIds;
            });
        }
原文地址:https://www.cnblogs.com/devilsky/p/5344381.html