使用c#的AppFabric缓存示例

ama*_*eur 26 c# caching appfabric

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

Phi*_*ove 45

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

// Create a factory reading the config info from the .config file
DataCacheFactory factory = new DataCacheFactory();
Run Code Online (Sandbox Code Playgroud)

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

DataCache myCache = factory.GetCache("myCache");
Run Code Online (Sandbox Code Playgroud)

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

object myCachedItem = new Object();
string myCachedItemKey = "MyCacheKey";
myCache.Add(myCachedItemKey, myCachedItem);
Run Code Online (Sandbox Code Playgroud)

从缓存中删除项目

myCache.Remove(myCachedItemKey);
Run Code Online (Sandbox Code Playgroud)

简单如.

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

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;
}
Run Code Online (Sandbox Code Playgroud)

更新缓存中的项目

// 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);
Run Code Online (Sandbox Code Playgroud)

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


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

  • @locster这是对这段代码的有效批评,虽然在我的(有限)防御中,它的目的是作为演示代码,而不是生产质量.当你开始研究并发机制时,它也很容易解决; AppFabric的一个漂亮功能是你可以在缓存中当前不存在的"GetAndLock"项目.因此,服务器1看到该项目不存在,因此它将其锁定以准备进行数据库调用.服务器2看到该项目不存在,尝试"GetAndLock"它并失败,因为服务器1已经有锁.见http://tinyurl.com/c5t6w45 (2认同)

小智 8

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

  • 128MB缓存现在包含10个连接 (4认同)