Nop中定义了ICacheManger接口,它有几个实现,其中MemoryCacheManager是内存缓存的一个实现。

MemoryCacheManager:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.Caching;
  4. using System.Text.RegularExpressions;
  5.  
  6. namespace Nop.Core.Caching
  7. {
  8. /// <summary>
  9. /// Represents a manager for caching between HTTP requests (long term caching)
  10. /// </summary>
  11. public partial class MemoryCacheManager : ICacheManager
  12. {
  13. /// <summary>
  14. /// Cache object
  15. /// </summary>
  16. protected ObjectCache Cache
  17. {
  18. get
  19. {
  20. return MemoryCache.Default;
  21. }
  22. }
  23.  
  24. /// <summary>
  25. /// Gets or sets the value associated with the specified key.
  26. /// </summary>
  27. /// <typeparam name="T">Type</typeparam>
  28. /// <param name="key">The key of the value to get.</param>
  29. /// <returns>The value associated with the specified key.</returns>
  30. public virtual T Get<T>(string key)
  31. {
  32. return (T)Cache[key];
  33. }
  34.  
  35. /// <summary>
  36. /// Adds the specified key and object to the cache.
  37. /// </summary>
  38. /// <param name="key">key</param>
  39. /// <param name="data">Data</param>
  40. /// <param name="cacheTime">Cache time</param>
  41. public virtual void Set(string key, object data, int cacheTime)
  42. {
  43. if (data == null)
  44. return;
  45.  
  46. var policy = new CacheItemPolicy();
  47. policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
  48. Cache.Add(new CacheItem(key, data), policy);
  49. }
  50.  
  51. /// <summary>
  52. /// Gets a value indicating whether the value associated with the specified key is cached
  53. /// </summary>
  54. /// <param name="key">key</param>
  55. /// <returns>Result</returns>
  56. public virtual bool IsSet(string key)
  57. {
  58. return (Cache.Contains(key));
  59. }
  60.  
  61. /// <summary>
  62. /// Removes the value with the specified key from the cache
  63. /// </summary>
  64. /// <param name="key">/key</param>
  65. public virtual void Remove(string key)
  66. {
  67. Cache.Remove(key);
  68. }
  69.  
  70. /// <summary>
  71. /// Removes items by pattern
  72. /// </summary>
  73. /// <param name="pattern">pattern</param>
  74. public virtual void RemoveByPattern(string pattern)
  75. {
  76. var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
  77. var keysToRemove = new List<String>();
  78.  
  79. foreach (var item in Cache)
  80. if (regex.IsMatch(item.Key))
  81. keysToRemove.Add(item.Key);
  82.  
  83. foreach (string key in keysToRemove)
  84. {
  85. Remove(key);
  86. }
  87. }
  88.  
  89. /// <summary>
  90. /// Clear all cache data
  91. /// </summary>
  92. public virtual void Clear()
  93. {
  94. foreach (var item in Cache)
  95. Remove(item.Key);
  96. }
  97.  
  98. /// <summary>
  99. /// Dispose
  100. /// </summary>
  101. public virtual void Dispose()
  102. {
  103. }
  104. }
  105. }

缓存的添加,在需要的地方构建cache key然后调用ICacheManger接口存储起来:

  1. var cachedModel = _cacheManager.Get(cacheKey, () =>
  2. {
  3. var model = new List<BlogPostYearModel>();
  4.  
  5. var blogPosts = _blogService.GetAllBlogPosts(_storeContext.CurrentStore.Id,
  6. _workContext.WorkingLanguage.Id);
  7. if (blogPosts.Count > )
  8. {
  9. var months = new SortedDictionary<DateTime, int>();
  10.  
  11. var first = blogPosts[blogPosts.Count - ].CreatedOnUtc;
  12. while (DateTime.SpecifyKind(first, DateTimeKind.Utc) <= DateTime.UtcNow.AddMonths())
  13. {
  14. var list = blogPosts.GetPostsByDate(new DateTime(first.Year, first.Month, ), new DateTime(first.Year, first.Month, ).AddMonths().AddSeconds(-));
  15. if (list.Count > )
  16. {
  17. var date = new DateTime(first.Year, first.Month, );
  18. months.Add(date, list.Count);
  19. }
  20.  
  21. first = first.AddMonths();
  22. }
  23.  
  24. int current = ;
  25. foreach (var kvp in months)
  26. {
  27. var date = kvp.Key;
  28. var blogPostCount = kvp.Value;
  29. if (current == )
  30. current = date.Year;
  31.  
  32. if (date.Year > current || model.Count == )
  33. {
  34. var yearModel = new BlogPostYearModel
  35. {
  36. Year = date.Year
  37. };
  38. model.Add(yearModel);
  39. }
  40.  
  41. model.Last().Months.Add(new BlogPostMonthModel
  42. {
  43. Month = date.Month,
  44. BlogPostCount = blogPostCount
  45. });
  46.  
  47. current = date.Year;
  48. }
  49. }
  50. return model;
  51. });

这个ICacheManger的Get方法其实是个扩展方法,当获取不到缓存的时候调用Func<T>获取值,然后缓存起来:

  1. using System;
  2.  
  3. namespace Nop.Core.Caching
  4. {
  5. /// <summary>
  6. /// Extensions
  7. /// </summary>
  8. public static class CacheExtensions
  9. {
  10. /// <summary>
  11. /// Get a cached item. If it's not in the cache yet, then load and cache it
  12. /// </summary>
  13. /// <typeparam name="T">Type</typeparam>
  14. /// <param name="cacheManager">Cache manager</param>
  15. /// <param name="key">Cache key</param>
  16. /// <param name="acquire">Function to load item if it's not in the cache yet</param>
  17. /// <returns>Cached item</returns>
  18. public static T Get<T>(this ICacheManager cacheManager, string key, Func<T> acquire)
  19. {
  20. return Get(cacheManager, key, , acquire);
  21. }
  22.  
  23. /// <summary>
  24. /// Get a cached item. If it's not in the cache yet, then load and cache it
  25. /// </summary>
  26. /// <typeparam name="T">Type</typeparam>
  27. /// <param name="cacheManager">Cache manager</param>
  28. /// <param name="key">Cache key</param>
  29. /// <param name="cacheTime">Cache time in minutes (0 - do not cache)</param>
  30. /// <param name="acquire">Function to load item if it's not in the cache yet</param>
  31. /// <returns>Cached item</returns>
  32. public static T Get<T>(this ICacheManager cacheManager, string key, int cacheTime, Func<T> acquire)
  33. {
  34. if (cacheManager.IsSet(key))
  35. {
  36. return cacheManager.Get<T>(key);
  37. }
  38.  
  39. var result = acquire();
  40. if (cacheTime > )
  41. cacheManager.Set(key, result, cacheTime);
  42. return result;
  43. }
  44. }
  45. }

Cache的移除。Nop缓存的移除比较有意思,它使用Pub/Sub模式来实现。

当你缓存一个Blog的列表,如果后面对某个Blog进行Update的时候,你就有两个选择:1.更新这个Blog的cache 2.移除所有关于Blog的cache。Nop选择的是后者,因为第一种方案实现起来的代价有点大,你可能需要给单独每个Blog指定一个Key来缓存起来,或者遍历所有关于Blog的cache。

当发生Blog的Update的时候,会发送一个通知事件:

  1. public virtual void UpdateBlogPost(BlogPost blogPost)
  2. {
  3. if (blogPost == null)
  4. throw new ArgumentNullException("blogPost");
  5.  
  6. _blogPostRepository.Update(blogPost);
  7.  
  8. //event notification
  9. _eventPublisher.EntityUpdated(blogPost);
  10. }

看一下EventPublish的实现 :

  1. public interface IEventPublisher
  2. {
  3. /// <summary>
  4. /// Publish event
  5. /// </summary>
  6. /// <typeparam name="T">Type</typeparam>
  7. /// <param name="eventMessage">Event message</param>
  8. void Publish<T>(T eventMessage);
  9. }
  10.  
  11. using System;
  12. using System.Linq;
  13. using Nop.Core.Infrastructure;
  14. using Nop.Core.Plugins;
  15. using Nop.Services.Logging;
  16.  
  17. namespace Nop.Services.Events
  18. {
  19. /// <summary>
  20. /// Evnt publisher
  21. /// </summary>
  22. public class EventPublisher : IEventPublisher
  23. {
  24. private readonly ISubscriptionService _subscriptionService;
  25.  
  26. /// <summary>
  27. /// Ctor
  28. /// </summary>
  29. /// <param name="subscriptionService"></param>
  30. public EventPublisher(ISubscriptionService subscriptionService)
  31. {
  32. _subscriptionService = subscriptionService;
  33. }
  34.  
  35. /// <summary>
  36. /// Publish to cunsumer
  37. /// </summary>
  38. /// <typeparam name="T">Type</typeparam>
  39. /// <param name="x">Event consumer</param>
  40. /// <param name="eventMessage">Event message</param>
  41. protected virtual void PublishToConsumer<T>(IConsumer<T> x, T eventMessage)
  42. {
  43. //Ignore not installed plugins
  44. var plugin = FindPlugin(x.GetType());
  45. if (plugin != null && !plugin.Installed)
  46. return;
  47.  
  48. try
  49. {
  50. x.HandleEvent(eventMessage);
  51. }
  52. catch (Exception exc)
  53. {
  54. //log error
  55. var logger = EngineContext.Current.Resolve<ILogger>();
  56. //we put in to nested try-catch to prevent possible cyclic (if some error occurs)
  57. try
  58. {
  59. logger.Error(exc.Message, exc);
  60. }
  61. catch (Exception)
  62. {
  63. //do nothing
  64. }
  65. }
  66. }
  67.  
  68. /// <summary>
  69. /// Find a plugin descriptor by some type which is located into its assembly
  70. /// </summary>
  71. /// <param name="providerType">Provider type</param>
  72. /// <returns>Plugin descriptor</returns>
  73. protected virtual PluginDescriptor FindPlugin(Type providerType)
  74. {
  75. if (providerType == null)
  76. throw new ArgumentNullException("providerType");
  77.  
  78. if (PluginManager.ReferencedPlugins == null)
  79. return null;
  80.  
  81. foreach (var plugin in PluginManager.ReferencedPlugins)
  82. {
  83. if (plugin.ReferencedAssembly == null)
  84. continue;
  85.  
  86. if (plugin.ReferencedAssembly.FullName == providerType.Assembly.FullName)
  87. return plugin;
  88. }
  89.  
  90. return null;
  91. }
  92.  
  93. /// <summary>
  94. /// Publish event
  95. /// </summary>
  96. /// <typeparam name="T">Type</typeparam>
  97. /// <param name="eventMessage">Event message</param>
  98. public virtual void Publish<T>(T eventMessage)
  99. {
  100. var subscriptions = _subscriptionService.GetSubscriptions<T>();
  101. subscriptions.ToList().ForEach(x => PublishToConsumer(x, eventMessage));
  102. }
  103.  
  104. }
  105. }

很简单,只是获取所有的订阅,然后依次调用其中的PublishToConsumer方法。

那么订阅是在哪里呢?

首先这是Blog消息消费者的定义:

  1. using Nop.Core.Caching;
  2. using Nop.Core.Domain.Blogs;
  3. using Nop.Core.Domain.Catalog;
  4. using Nop.Core.Domain.Configuration;
  5. using Nop.Core.Domain.Directory;
  6. using Nop.Core.Domain.Localization;
  7. using Nop.Core.Domain.Media;
  8. using Nop.Core.Domain.News;
  9. using Nop.Core.Domain.Orders;
  10. using Nop.Core.Domain.Polls;
  11. using Nop.Core.Domain.Topics;
  12. using Nop.Core.Domain.Vendors;
  13. using Nop.Core.Events;
  14. using Nop.Core.Infrastructure;
  15. using Nop.Services.Events;
  16.  
  17. namespace Nop.Web.Infrastructure.Cache
  18. {
  19. /// <summary>
  20. /// Model cache event consumer (used for caching of presentation layer models)
  21. /// </summary>
  22. public partial class ModelCacheEventConsumer:
  23.  
  24. //blog posts
  25. IConsumer<EntityInserted<BlogPost>>,
  26. IConsumer<EntityUpdated<BlogPost>>,
  27. IConsumer<EntityDeleted<BlogPost>>
  28.  
  29. {
  30. /// <summary>
  31. /// Key for blog tag list model
  32. /// </summary>
  33. /// <remarks>
  34. /// {0} : language ID
  35. /// {1} : current store ID
  36. /// </remarks>
  37. public const string BLOG_TAGS_MODEL_KEY = "Nop.pres.blog.tags-{0}-{1}";
  38. /// <summary>
  39. /// Key for blog archive (years, months) block model
  40. /// </summary>
  41. /// <remarks>
  42. /// {0} : language ID
  43. /// {1} : current store ID
  44. /// </remarks>
  45. public const string BLOG_MONTHS_MODEL_KEY = "Nop.pres.blog.months-{0}-{1}";
  46. public const string BLOG_PATTERN_KEY = "Nop.pres.blog";
  47.  
  48. private readonly ICacheManager _cacheManager;
  49.  
  50. public ModelCacheEventConsumer()
  51. {
  52. //TODO inject static cache manager using constructor
  53. this._cacheManager = EngineContext.Current.ContainerManager.Resolve<ICacheManager>("nop_cache_static");
  54. }
  55.  
  56. //Blog posts
  57. public void HandleEvent(EntityInserted<BlogPost> eventMessage)
  58. {
  59. _cacheManager.RemoveByPattern(BLOG_PATTERN_KEY);
  60. }
  61. public void HandleEvent(EntityUpdated<BlogPost> eventMessage)
  62. {
  63. _cacheManager.RemoveByPattern(BLOG_PATTERN_KEY);
  64. }
  65. public void HandleEvent(EntityDeleted<BlogPost> eventMessage)
  66. {
  67. _cacheManager.RemoveByPattern(BLOG_PATTERN_KEY);
  68. }
  69. }
  70. }

所有的Blog的key都采用统一的前缀,Nop.pres.blog。这样只要使用这个前缀就能清楚所有关于blog的缓存了。

这个类继承了3个接口所以有3个HandleEvent的实现,都是清楚blog相关的缓存。

这些消费者其实并未主动的去注册订阅,而是通过反射在启动的时候自动加载进IoC容器里的,当需要使用的时候通过接口直接取出来使用。

  1. //Register event consumers
  2. var consumers = typeFinder.FindClassesOfType(typeof(IConsumer<>)).ToList();
  3. foreach (var consumer in consumers)
  4. {
  5. builder.RegisterType(consumer)
  6. .As(consumer.FindInterfaces((type, criteria) =>
  7. {
  8. var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
  9. return isMatch;
  10. }, typeof(IConsumer<>)))
  11. .InstancePerLifetimeScope();
  12. }
  13. builder.RegisterType<EventPublisher>().As<IEventPublisher>().SingleInstance();
  14. builder.RegisterType<SubscriptionService>().As<ISubscriptionService>().SingleInstance();

其中Pub/Sub是其中的精髓,非常值得学习。

Nop中的Cache浅析的更多相关文章

  1. JavaScript中闭包之浅析解读

    JavaScript中的闭包真心是一个老生常谈的问题了,最近面试也是一直问到,我自己的表述能力又不能完全支撑起来,真是抓狂.在回来的路上,我突然想到了一个很简单的事情,其实我们在做项目时候,其实就经常 ...

  2. [转]学习Nop中Routes的使用

    本文转自:http://www.cnblogs.com/miku/archive/2012/09/27/2706276.html 1. 映射路由 大型MVC项目为了扩展性,可维护性不能像一般项目在Gl ...

  3. cache 浅析

    http://blog.chinaunix.net/uid-26817832-id-3244916.html   1. Cache Cache一词来源于法语,其原意是"藏匿处,隐秘的地方&q ...

  4. Linux内存中的Cache真的能被回收么?

    在Linux系统中,我们经常用free命令来查看系统内存的使用状态.在一个RHEL6的系统上,free命令的显示内容大概是这样一个状态: [root@tencent64 ~]# free       ...

  5. 在Spring中使用cache(EhCache的对象缓存和页面缓存)

    Spring框架从version3.1开始支持cache,并在version4.1版本中对cache功能进行了增强. spring cache 的关键原理就是 spring AOP,通过 spring ...

  6. 浅谈数据库系统中的cache

    Cache和Buffer是两个不同的概念,简单的说,Cache是加速“读”,而buffer是缓冲“写”,前者解决读的问题,保存从磁盘上读出的数据,后者是解决写的问题,保存即将要写入到磁盘上的数据.在很 ...

  7. Linux内核中的Cache段

    Linux内核中的Cache段 原文地址:http://blogold.chinaunix.net/u2/85263/showart_1743693.html 最近移植LEON3的内核时,了解了一些简 ...

  8. Linux 内存中的Cache,真的能被回收么?

    您真的了解Linux的free命令么? 在Linux系统中,我们经常用free命令来查看系统内存的使用状态.在一个RHEL6的系统上,free命令的显示内容大概是这样一个状态: 这里的默认显示单位是k ...

  9. Linux内核中内存cache的实现【转】

    Linux内核中内存cache的实现 转自:http://blog.chinaunix.net/uid-127037-id-2919545.html   本文档的Copyleft归yfydz所有,使用 ...

随机推荐

  1. Java面试查漏补缺

    一.基础 1.&和&&的区别. [概述] &&只能用作逻辑与(and)运算符(具有短路功能):但是&可以作为逻辑与运算符(是“无条件与”,即没有短路的功 ...

  2. poj1200-Crazy Search(hash入门经典)

    Hash:一般是一个整数.就是说通过某种算法,可以把一个字符串"压缩" 成一个整数.一,题意: 给出两个数n,nc,并给出一个由nc种字符组成的字符串.求这个字符串中长度为n的不同 ...

  3. C#_基础:委托速讲

    1定义:委托=函数指针 C# public delegate void Test(string str); 等价C++ public void (*Test)(string str): 委托赋值(初始 ...

  4. 《Linux内核设计与实现》读书笔记 第四章 进程调度

    第四章进程调度 进程调度程序可看做在可运行太进程之间分配有限的处理器时间资源的内核子系统.调度程序是多任务操作系统的基础.通过调度程序的合理调度,系统资源才能最大限度地发挥作用,多进程才会有并发执行的 ...

  5. MongoDB 初见指南

    技术若只如初见,那么还会踩坑么? 在系统引入 MongoDB 也有几年了,一开始是因为 MySQL 中有单表记录增长太快(每天几千万条吧)容易拖慢 MySQL 的主从复制.而这类数据增长迅速的流水表, ...

  6. Javascript基础回顾 之(一) 类型

    本来是要继续由浅入深表达式系列最后一篇的,但是最近团队突然就忙起来了,从来没有过的忙!不过喜欢表达式的朋友请放心,已经在写了:) 在工作当中发现大家对Javascript的一些基本原理普遍存在这里或者 ...

  7. 《Entity Framework 6 Recipes》中文翻译系列 (20) -----第四章 ASP.NET MVC中使用实体框架之在MVC中构建一个CRUD示例

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 第四章  ASP.NET MVC中使用实体框架 ASP.NET是一个免费的Web框架 ...

  8. JS.中文乱码,Jsp\Servlet端的解决办法

    JS.中文乱码,Jsp\Servlet端的解决办法 2010-03-08 15:18:21|  分类: Extjs |  标签:encodeuricomponent  乱码  urldecoder   ...

  9. 集群下session共享问题的解决方案.

    这一篇博客来讲解下babasport这个项目中使用的Login功能, 当然这里说的只是其中的一些简单的部分, 记录在此 方便以后查阅. 一: 去登录页面首先我们登录需要注意的事项是, 当用户点击登录按 ...

  10. Atitit.数据索引 的种类以及原理实现机制 索引常用的存储结构

    Atitit.数据索引 的种类以及原理实现机制 索引常用的存储结构 1. 索引的分类1 1.1. 按照存储结构划分btree,hash,bitmap,fulltext1 1.2. 索引的类型  按查找 ...