使用c#的AppFabric缓存示例

时间:2011-01-19 19:11:15

标签: c# caching appfabric

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

2 个答案:

答案 0 :(得分:45)

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

// 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 Server AppFabric培训套件here,其中有一节 缓存。请继续关注appfabric标签,因为我确信随着时间的推移会有更多代码示例为人们解决问题。

答案 1 :(得分:8)

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