我目前正在研究将AppFabric缓存集成到我的.net c#应用程序中,并寻找一些相关的代码示例。是否有任何关于AppFabric缓存的开源或示例代码可供我参考?
缓存操作
在处理 AppFabric 缓存时,首先要创建的对象是 DataCacheFactory
。这可以通过硬编码的配置数据来创建,告诉工厂如何联系缓存服务器,或者不使用任何配置,此时它会从您的 web.config/app.config 文件中读取配置。我的建议是将配置信息保留在 .config 文件中,否则当您想要更改缓存设置中的某些内容时,就需要重新编译和重新分发应用程序。关于 DataCacheFactory 需要记住的重要事情是它很昂贵,您绝对不想为每个缓存操作创建一个 DataCacheFactory 实例。考虑使用单例模式 - 有关详细信息,请参见此问题。
// Create a factory reading the config info from the .config file
DataCacheFactory factory = new DataCacheFactory();
缓存的主要接口是通过 Cache
对象实现的。可以通过 DataCacheFactory 的 GetCache
方法获取缓存,需要传入缓存的名称:
DataCache myCache = factory.GetCache("myCache");
向缓存添加项目
缓存中的每个项目都有一个字符串键。键必须对于缓存是唯一的 - 如果您传递一个已经存在的键,您将收到一个异常。要缓存的项目必须是可序列化的,因此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服务器应用程序集成服务培训工具包,其中包含有关缓存的部分。请继续关注appfabric标签,随着时间的推移,我相信会有更多的代码示例解决人们的问题。
GetAndLock
那些当前不存在于缓存中的项目。因此,服务器1发现该项目不存在,所以它锁定该项目以准备进行数据库调用。服务器2发现该项目不存在,试图GetAndLock
它,但失败了,因为服务器1已经锁定了该项目。请参阅http://tinyurl.com/c5t6w45 - PhilPursglove