使用c#的AppFabric缓存示例

我目前正在研究将AppFabirc缓存集成到我的.net c#应用程序中,并寻找一些代码示例。 有没有可用的AppFabric缓存可用的开源或代码示例我可以看一下?

缓存操作
处理AppFabric缓存时创建的第一个对象是DataCacheFactory 。 这可以使用硬编码配置数据创建,该数据告诉工厂如何联系缓存服务器,或者没有配置,在这种情况下,它从web.config / app.config文件中读取配置。 我的建议是将配置信息保存在.config文件中,否则当您想要更改缓存设置中的某些内容时,您需要重新编译并重新分发您的应用程序。 关于DataCacheFactory要记住的重要一点是创建起来很昂贵 – 你肯定不想为每个缓存操作创建其中一个。 考虑使用Singleton模式 – 请参阅此问题以获取更多详细信息。

 // Create a factory reading the config info from the .config file DataCacheFactory factory = new DataCacheFactory(); 

缓存的主要接口是通过Cache对象。 从DataCacheFactory的GetCache方法获取Cache,传入缓存的名称:

 DataCache myCache = factory.GetCache("myCache"); 

将项添加到缓存中
缓存中的每个项都有一个键,它是一个字符串。 密钥必须是缓存唯一的 – 如果传入已存在的密钥,您将获得exception。 要缓存的项目必须是可序列化的,因此AppFabric可以在内部将其传递到缓存中的服务器。 在最基本的级别,使用Add方法将项添加到缓存中。

 object myCachedItem = new Object(); string myCachedItemKey = "MyCacheKey"; myCache.Add(myCachedItemKey, myCachedItem); 

从缓存中删除项目

 myCache.Remove(myCachedItemKey); 

简单如。

从缓存中获取项目
从缓存中获取项目时,我们使用缓存模式。 这意味着我们查看缓存以查看是否存在所需的项目(使用密钥)。 如果项目在缓存中,我们将获取缓存项目(可能将其转换为其他类型); 否则我们会采取措施从头开始获取项目,例如从数据库中读取,然后将其缓存,以便下次为我们提供。

 object cachedObject; string myImportantDataKey = "MyImportantDataTable"; DataTable myImportantData; // This is an object because everything is returned from the cache as an object cachedObject = myCache.Get(myImportantDataKey); // Check to see if we got something from the cache if (cachedObject == null) { // The requested item wasn't in the cache - a cache miss // Go get the data from the db myImportantData = getMyImportantDataFromMyDatabase(); // Add the item to the cache so we've got it for next time myCache.Add(myImportantDataKey, myImportantData); } else { // We have the cached object so cast it to a DataTable myImportantData = (DataTable)cachedObject; } 

更新缓存中的项目

 // Put can be used to update an existing item in the cache // If the item does not exist then it functions like Add myCache.Put(myImportantDataKey, myUpdatedImportantData); 

这是基本的CRUD操作,但是你可以用更多的东西来处理并发!


Windows Server AppFabric培训套件可以在这里下载,它有一个关于缓存的部分。 请继续关注appfabric标签,因为我确信随着时间的推移,会有更多的代码示例为人们解决问题。

另外值得一提的是,如果您使用Azure AppFabric缓存服务,则Singleton模式非常重要,因为DataCacheFactory的每个实例都会创建一个到Azure AppFabric缓存服务的新连接。 由于连接数量受限于缓存大小(128MB缓存包含5个连接),如果不重复使用同一工厂,您将非常快速地锁定所有连接!