在查找资料的过程中。原来园子里面已经有过分析了。nopCommerce架构分析系列(二)数据Cache。 接下来是一些学习补充。

1.Nop中没有System.Web.Caching.Cache的实现。原因暂不明。先自己实现一个吧

using System;
using System.Collections.Generic;
using System.Web;
using System.Runtime.CompilerServices;
using System.Web.Caching;
using System.Collections;
using System.Text.RegularExpressions; namespace SDF.Core.Caching
{ public class CacheManager : ICacheManager
{
System.Web.Caching.Cache Cache = HttpRuntime.Cache; public void Set(string key, object data)
{
Cache.Insert(key, data);
}
public void Set(string key, object data, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
Cache.Insert(key, data, null,absoluteExpiration, slidingExpiration);
} public object Get(string Key)
{
return Cache[Key];
} public T Get<T>(string key)
{
return (T)Cache[key];
} public bool IsSet(string key)
{
return Cache[key] != null;
} public void Remove(string Key)
{
if (Cache[Key] != null) {
Cache.Remove(Key);
}
} public void RemoveByPattern(string pattern)
{
IDictionaryEnumerator enumerator = Cache.GetEnumerator();
Regex rgx = new Regex(pattern, (RegexOptions.Singleline | (RegexOptions.Compiled | RegexOptions.IgnoreCase)));
while (enumerator.MoveNext()) {
if (rgx.IsMatch(enumerator.Key.ToString())) {
Cache.Remove(enumerator.Key.ToString());
}
}
} public void Clear()
{
IDictionaryEnumerator enumerator = Cache.GetEnumerator();
while (enumerator.MoveNext())
{
Cache.Remove(enumerator.Key.ToString());
}
} } }

2.MemoryCache 和 ASP.NET Cache 区别。

引用MSDN

MemoryCache 类类似于 ASP.NET Cache 类。 MemoryCache 类有许多用于访问缓存的属性和方法,如果您使用过 ASP.NET Cache 类,您将熟悉这些属性和方法。 Cache 和 MemoryCache 类之间的主要区别是:MemoryCache 类已被更改,以便 .NET Framework 应用程序(非 ASP.NET 应用程序)可以使用该类。 例如,MemoryCache 类对 System.Web 程序集没有依赖关系。 另一个差别在于您可以创建 MemoryCache 类的多个实例,以用于相同的应用程序和相同的 AppDomain 实例。

代码更清楚一点:

[Test]
public void MemoryCacheTest()
{
var cache = new MemoryCache("cache1");
var cache2 = new MemoryCache("cache2");
var policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes();
cache.Set(new CacheItem("key1", "data1"), policy); var obj = cache.Get("key1");
Assert.IsNotNull(obj); var obj2 = cache2.Get("key1");
Assert.IsNull(obj2);
}

3.Nop中IOC和ICache

注册CacheManager

//cache manager
builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();
builder.RegisterType<PerRequestCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_per_request").InstancePerHttpRequest();

注册Service(可以根据实际需求为Service提供不同的缓存方式。)

//pass MemoryCacheManager to SettingService as cacheManager (cache settngs between requests)
builder.RegisterType<SettingService>().As<ISettingService>()
.WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
.InstancePerHttpRequest();
//pass MemoryCacheManager to LocalizationService as cacheManager (cache locales between requests)
builder.RegisterType<LocalizationService>().As<ILocalizationService>()
.WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
.InstancePerHttpRequest(); //pass MemoryCacheManager to LocalizedEntityService as cacheManager (cache locales between requests)
builder.RegisterType<LocalizedEntityService>().As<ILocalizedEntityService>()
.WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
.InstancePerHttpRequest();

最后是构造器注入

/// <summary>
/// Provides information about localizable entities
/// </summary>
public partial class LocalizedEntityService : ILocalizedEntityService
{
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="localizedPropertyRepository">Localized property repository</param>
public LocalizedEntityService(ICacheManager cacheManager,
IRepository<LocalizedProperty> localizedPropertyRepository)
{
this._cacheManager = cacheManager;
this._localizedPropertyRepository = localizedPropertyRepository;
}
}

4.Cache的使用

一段Nop中的代码

private const string BLOGPOST_BY_ID_KEY = "Nop.blogpost.id-{0}";
private const string BLOGPOST_PATTERN_KEY = "Nop.blogpost."; /// <summary>
/// Gets a blog post
/// </summary>
/// <param name="blogPostId">Blog post identifier</param>
/// <returns>Blog post</returns>
public virtual BlogPost GetBlogPostById(int blogPostId)
{
if (blogPostId == )
return null; string key = string.Format(BLOGPOST_BY_ID_KEY, blogPostId);
return _cacheManager.Get(key, () =>
{
var pv = _blogPostRepository.GetById(blogPostId);
return pv;
});
}/// <summary>
/// Updates the blog post
/// </summary>
/// <param name="blogPost">Blog post</param>
public virtual void UpdateBlogPost(BlogPost blogPost)
{
if (blogPost == null)
throw new ArgumentNullException("blogPost"); _blogPostRepository.Update(blogPost); _cacheManager.RemoveByPattern(BLOGPOST_PATTERN_KEY); //event notification
_eventPublisher.EntityUpdated(blogPost);
}

在查找数据时,会先从缓存中读取,更新数据时再清空缓存。 但是在这里Update了一个blogPost对象。没有必要把所有的blogPost缓存全部清空掉。稍微改一下

/// <summary>
/// Updates the blog post
/// </summary>
/// <param name="blogPost">Blog post</param>
public virtual void UpdateBlogPostV2(BlogPost blogPost)
{
if (blogPost == null)
throw new ArgumentNullException("blogPost"); _blogPostRepository.Update(blogPost); string key = string.Format(BLOGPOST_BY_ID_KEY, blogPost.Id);
_cacheManager.Remove(key); //event notification
_eventPublisher.EntityUpdated(blogPost);
}

总结:nop提供了易于扩展的Cache类,以及很好的使用实践。非常有借鉴和学习使用的意义。 只需稍微改造一下就可以用于自己的项目中。

ASP.NET Cache 类的更多相关文章

  1. System.Web.Caching.Cache类 Asp.Net缓存 各种缓存依赖

    Cache类,是一个用于缓存常用信息的类.HttpRuntime.Cache以及HttpContext.Current.Cache都是该类的实例. 一.属性 属性 说明 Count 获取存储在缓存中的 ...

  2. ASP.NET Cache的一些总结分享

    最近我们的系统面临着严峻性能瓶颈问题,这是由于访问量增加,客户端在同一时间请求增加,这迫使我们要从两个方面解决这一问题,增加硬件和提高系统的性能. 1.1.1 摘要 最近我们的系统面临着严峻性能瓶颈问 ...

  3. ASP.NET Cache

    ASP.NET为了方便我们访问Cache,在HttpRuntime类中加了一个静态属性Cache,这样,我们就可以在任意地方使用Cache的功能. 而且,ASP.NET还给它增加了二个“快捷方式”:P ...

  4. 细说 ASP.NET Cache 及其高级用法

    许多做过程序性能优化的人,或者关注过程程序性能的人,应该都使用过各类缓存技术. 而我今天所说的Cache是专指ASP.NET的Cache,我们可以使用HttpRuntime.Cache访问到的那个Ca ...

  5. System.Web.Caching.Cache类 缓存 各种缓存依赖

    原文:System.Web.Caching.Cache类 缓存 各种缓存依赖 Cache类,是一个用于缓存常用信息的类.HttpRuntime.Cache以及HttpContext.Current.C ...

  6. 细说 ASP.NET Cache 及其高级用法【转】

    阅读目录 开始 Cache的基本用途 Cache的定义 Cache常见用法 Cache类的特点 缓存项的过期时间 缓存项的依赖关系 - 依赖其它缓存项 缓存项的依赖关系 - 文件依赖 缓存项的移除优先 ...

  7. Cache类缓存

    此处主要总结System.Web.Caching.Cache类 该类是用于存储常用信息的类,HttpRuntime.Cache以及HttpContext.Current.Cache都是该类的实例. 该 ...

  8. [转]细说 ASP.NET Cache 及其高级用法

    本文转自:http://www.cnblogs.com/fish-li/archive/2011/12/27/2304063.html 阅读目录 开始 Cache的基本用途 Cache的定义 Cach ...

  9. System.Web.Caching.Cache类 缓存 各种缓存依赖(转)

    转自:http://www.cnblogs.com/kissdodog/archive/2013/05/07/3064895.html Cache类,是一个用于缓存常用信息的类.HttpRuntime ...

随机推荐

  1. Quartz 2D中的基本图形绘制

    在iOS中绘图一般分为以下几个步骤: 1.获取绘图上下文 2.创建并设置路径 3.将路径添加到上下文 4.设置上下文状态 5.绘制路径 6.释放路径 在UIKit中默认已经为我们准备好了一个图形上下文 ...

  2. SpringMvc+thymeleaf+HTML5中文乱码问题

    SpringMvc+thymeleaf+HTML5环境下遇到中文乱码...... 按照以往经验逐个排查,开发环境统一为utf-8编码,服务器也配置了编码过滤器,tomcat也是utf-8编码.前台页面 ...

  3. composer安装自己的包

    composer的出现,使得PHPer可以像Java一样更加方便的管理代码.在composer没有出现之前,人们大多使用pear.pecl管理依赖,但是局限性很多,也很少有人用(接触的大多phper基 ...

  4. HDU 5798 Stabilization

    方法太厉害了....看了官方题解的做法....然后...想了很久很久才知道他想表达什么.... #pragma comment(linker, "/STACK:1024000000,1024 ...

  5. iOS UIApplication 里面各const实际用意

    //后台通知:屏幕操作通知等等 UIKIT_EXTERN NSString *const UIApplicationDidEnterBackgroundNotification       NS_AV ...

  6. where条件的lambda转化为sql语句

    网上找的源码,但是博主说有bug 让自己调试.这个是我经过多次修改后的代码,可以直接用 public static class LambdaToSqlHelper { #region 基础方法 #re ...

  7. 如何查找僵尸进程并Kill之,杀不掉的要查看父进程并杀之

    转自:如何查找僵尸进程并Kill之,杀不掉的要查看父进程并杀之 用ps和grep命令寻找僵尸进程#ps -A -ostat,ppid,pid,cmd | grep -e '^[Zz]'命令注解:-A ...

  8. thinkphp 实现微信公众号开发(二)--实现自定义菜单

    IndexController.class.php <?php namespace Home\Controller; use Think\Controller; class IndexContr ...

  9. hdu_1728_逃离迷宫(bfs)

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1728 题意:走迷宫,找最小的拐角 题解:对BFS有了新的理解,DFS+剪枝应该也能过,用BFS就要以拐 ...

  10. Mayor's posters问题处理

    题目的感悟: /*这道题的想法是先开一个数组,先构造一颗线段树,然后每次都进行一次更新最后我们在访问的时候只要看最外层还剩下那些数字,对他们进行统计然后将结果返回即可.这道题的难度本来是不大的,思路非 ...