我的NopCommerce之旅(5): 缓存
2024-10-21 06:32:52
一、基础介绍
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。
//cache managers
if (config.RedisCachingEnabled)
{
builder.RegisterType<RedisCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").InstancePerLifetimeScope();
}
else
{
builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();
}
2.2.RedisCachingEnabled通过读取配置文件,见Nop.Core.Configuration.NopConfig
var redisCachingNode = section.SelectSingleNode("RedisCaching");
if (redisCachingNode != null && redisCachingNode.Attributes != null)
{
var enabledAttribute = redisCachingNode.Attributes["Enabled"];
if (enabledAttribute != null)
config.RedisCachingEnabled = Convert.ToBoolean(enabledAttribute.Value); var connectionStringAttribute = redisCachingNode.Attributes["ConnectionString"];
if (connectionStringAttribute != null)
config.RedisCachingConnectionString = connectionStringAttribute.Value;
}
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;
});
}
最新文章
- 【清北学堂】 死亡(death)
- 线程,yield让出cpu调度
- [原][CSS3]会动的盒子机器人
- sqlite 报错:database is locked
- mysql中的null字段值的处理及大小写问题
- [Java A] – is not an enclosing class
- innobackupex 备份实验
- Oracle 监听动态注册与静态注册
- 帕累托分析法(Pareto Analysis)(柏拉图分析)
- 【解决方法】System.IO.FileNotFoundException
- poj 1872 A Dicey Problem WA的代码,望各位指教!!!
- 关于文件上传的ajax交互
- SPP-Net理解
- ARouter学习随笔
- 《转》:JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解
- ArcGIS鼠标滚轮方向之代码篇
- IDEA中静态资源无法找到的原因
- Laravel 5.5处理 Emoji 表情不顯示問題
- django的forms
- go-处理字符串导致内存溢出