为了提高一个系统或网站的性能和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, , 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 > )
    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

nopCommerce 数据缓存的更多相关文章

  1. Servlet数据缓存

    缓存是提高数据访问能力,降低服务器压力的一种必要的方式,今天我要说的数据缓存方式有两种,1-->session对单个数据访问接口页面的数据进行缓存,2-->单例模式对整个servlet页面 ...

  2. 面localStorage用作数据缓存的简易封装

    面localStorage用作数据缓存的简易封装 最近做了一些前端控件的封装,需要用到数据本地存储,开始采用cookie,发现很容易就超过了cookie的容量限制,于是改用localStorage,但 ...

  3. jQuery数据缓存方案详解:$.data()的使用

    我们经常使用隐藏控件或者是js全局变量来临时存储数据,全局变量容易导致命名污染,隐藏控件导致经常读写dom浪费性能.jQuery提供了自己的数据缓存方案,能够达到和隐藏控件.全局变量相同的效果,但是j ...

  4. jQuery 2.0.3 源码分析 数据缓存

    历史背景: jQuery从1.2.3版本引入数据缓存系统,主要的原因就是早期的事件系统 Dean Edwards 的 ddEvent.js代码 带来的问题: 没有一个系统的缓存机制,它把事件的回调都放 ...

  5. SQL Server 数据缓存

    引言 SQL Server通过一些工具来监控数据,其中之一的方法就是动态管理管理视图(DMV). 常规动态服务器管理对象 dm_db_*:数据库和数据库对象 dm_exec_*:执行用户代码和关联的连 ...

  6. iOS开发网络篇—数据缓存

      iOS开发网络篇—数据缓存 一.关于同一个URL的多次请求 有时候,对同一个URL请求多次,返回的数据可能都是一样的,比如服务器上的某张图片,无论下载多少次,返回的数据都是一样的. 上面的情况会造 ...

  7. Memcache,Redis,MongoDB(数据缓存系统)方案对比与分析

    mongodb和memcached不是一个范畴内的东西.mongodb是文档型的非关系型数据库,其优势在于查询功能比较强大,能存储海量数据.mongodb和memcached不存在谁替换谁的问题. 和 ...

  8. 微信小程序-数据缓存

    每个微信小程序都可以有自己的本地缓存,可以通过 wx.setStorage(wx.setStorageSync).wx.getStorage(wx.getStorageSync).wx.clearSt ...

  9. Memcached 数据缓存系统

    Memcached 数据缓存系统 常用命令及使用:http://www.cnblogs.com/wayne173/p/5652034.html Memcached是一个自由开源的,高性能,分布式内存对 ...

随机推荐

  1. ruby 安装更新

    wget http://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.2.tar.gz tar xfvz ruby-2.2.2.tar.gz cd ruby-2. ...

  2. 使用Java程序调用MatLab

    Java代码实现的计算难免会显得不够高效.而利用MATLAB写好相应的计算函数,然后打包成jar包供Java调用,在某些情况下会更加方便.或者有些时候会涉及到使用Java调用MatLab展现一些二维三 ...

  3. HTML5每日一练之progress标签的应用

    progress标签:从名字上来看,估计大家也能猜到这个标签是什么标签了,没错,他是一个进度条.在HTML5中我们终于可以不用模拟了. <progress id="W3Cfuns_pr ...

  4. SPI移位寄存器

    spi移位寄存器即是spi的数据寄存器,在stm32中数据手册是这样描述的:

  5. Database事件研究

    1.Database.ObjectAppended.ObjectModified.ObjectErased事件 此事件如果不是Transaction提交而触发的,那么可以在事件内部使用Transact ...

  6. ThinkPad X220i 刷白名单BIOS,改装第三方无线网卡

    ThinkPad X220i自带的网卡是REALTEK RTL8188CE,这张卡在Mac下目前是无解的.国外网站有该卡liunx.unix内核的驱动,但还是没有高人编译出来. 不等了,这卡没戏.正好 ...

  7. 关于缺省路由传递问题的探讨(下)[ip default-network、ip default-gateway等]

    之前文章介绍的是没有路由协议的环境下,那么在有路由协议的环境下: ip default-network IGRP/EIGRP: IP Default-Network所指定的网络必须在EIGRP进程中通 ...

  8. redis缓存数据表

    直观上看,数据库中的数据都是按表存储的:更微观地看,这些表都是按行存储的.每执行一 次select查询,数据库都会返回一个结果集,这个结果集由若干行组成.所以,一个自然而然 的想法就是在Redis中找 ...

  9. Codeforces 712 D. Memory and Scores (DP+滚动数组+前缀和优化)

    题目链接:http://codeforces.com/contest/712/problem/D A初始有一个分数a,B初始有一个分数b,有t轮比赛,每次比赛都可以取[-k, k]之间的数,问你最后A ...

  10. CentOS常用查看系统命令

    系统 uname -a                 查看内核/操作系统/CPU信息head -n 1 /etc/issue  查看操作系统版本cat /proc/cpuinfo       查看C ...