65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Windows Azure AppFabric 缓存 (CTP)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.96/5 (12投票s)

2011 年 2 月 16 日

CPOL

6分钟阅读

viewsIcon

60304

downloadIcon

525

如何设置和使用 Windows Azure AppFabric 缓存 (CTP)。

引言

每天需要服务数百万用户的高度可扩展应用程序需要一个高度可扩展、高可用且持久的缓存平台和架构。分布式缓存节点几乎总是避免不必要地往返数据库的最佳解决方案,但如果实施不当,它们也可能导致问题。可能出现的问题包括使用包含旧版本数据的过时对象,或者未能从缓存中检索到正确的(不一定是最新版本)对象,或者对象过早地从缓存中过期。

在最新 CTP 版本的 Windows Azure AppFabric 中,其中一个最受期待的功能得到了显著增强。缓存在 PDC '10 中与服务总线上的持久消息、更多身份联合的身份提供者、VM 角色、超小实例、SQL Azure 报告、Windows Azure Connect 等其他功能一起推出。

本文基于 Visual Studio 2010,使用当时发布的最新版本 Windows Azure SDK v1.3,以及 Windows Azure AppFabric SDK v2.0 CTP 2 月版本。

背景

早些时候,Windows Azure AppFabric Cache 被称为“Velocity”,但这不仅是 Windows Azure AppFabric 的一部分,也是 Windows Server AppFabric 的一部分,其中还包括一个代号为“Dublin”的项目。“Dublin”也被演示为一个复合构建服务,您可以选择应用程序所有必要的组件,并结合 WCF 和 WF 托管和编排,获得许多新功能,例如轻松扩展,以及通过点击添加新组件/服务到应用程序。所有这些都只是 Windows Azure/Server AppFabric 系列中包含内容的快速概述。请注意,它们并非完全一致,这意味着如果某个功能存在于 Windows Azure AppFabric 中,并不意味着它也存在于 Windows Server AppFabric 中。

这是什么?

Windows Azure AppFabric Cache 提供了平台即服务 (PaaS) 方法,就像整个 Windows Azure 平台一样,消除了设置带有节点的新缓存场以及设置所有必要设置以保持这些节点同步、确保节点有足够资源等方面的麻烦。您所要做的就是访问 http://portal.appfabriclabs.com,注册并开始使用 Windows Azure AppFabric 提供的一切服务,包括 ACL、服务总线和缓存。

它是如何工作的?

与其他任何分布式缓存解决方案一样,Windows Azure AppFabric Cache 包含两部分。服务器部分(服务运行的地方)和客户端部分(客户端使用代码和配置来访问它)。要创建服务器部分,您必须访问前面提到的 Windows Azure AppFabric Labs 门户并选择“Cache”。

之后,您需要点击“创建命名空间”。

Create-namespace-red.png

在那里您必须选择一个订阅来激活该功能。由于这是一个 CTP 功能,您目前不会有任何已创建的订阅,因此门户会提示您自动创建一个。点击“确定”后,您将获得一个名为“LabsSubscription”的新订阅。由于您无法在 CTP 中创建新订阅,因此所有内容都将与此订阅关联。当订阅准备好后(需要 3-4 秒),您必须为您的命名空间选择一个名称,然后检查它是否可用,然后选择区域(CTP 仅提供美国),最后选择缓存大小,可以是 128 MB 或 256 MB。如果您愿意,可以每 24 小时更改一次缓存大小。

create-new-cache-namespace.png

现在您可以点击“确定”,命名空间将暂时处于“正在激活”状态。

activating-activated.png

当它准备就绪时,它会变成绿色,并显示“已激活”,这意味着您现在可以在应用程序中使用它了。正如我所说,应用程序包含两部分;我们刚刚激活了服务器部分,现在我们将创建客户端配置来访问该服务。这部分也由门户自动完成。

Manage-namespace.png

您所要做的就是点击“确定”,“查看客户端配置”,然后选择您需要的正确配置部分,无论是用于非 Web 应用程序还是 Web 应用程序,在 Web 应用程序中,您可以将会话状态持久化存储更改为此缓存。在同一菜单中,您还可以通过点击“更改缓存大小”来更改缓存大小。如果您点击“查看客户端配置”,您会得到一个窗口,其中包含您需要放入您的 app.configweb.config 中的所有必要 XML。

client-configuration.png

选择您应用程序所需的部分后(在我的例子中是一个简单的控制台应用程序,用于演示如何使用缓存的一些非常基本的知识),您需要将其放置在您的 app.config 中。

<configuration>
  <configsections>
    <section name="dataCacheClient" 
       type="Microsoft.ApplicationServer.Caching.DataCacheClientSection, 
             Microsoft.ApplicationServer.Caching.Core" 
       allowlocation="true" allowdefinition="Everywhere">
  </section></configsections>

  <datacacheclient deployment="Simple">
    <hosts>
      <host name="YOUR_NAMESPACE.cache.appfabriclabs.com" 
                       cacheport="22233">
    </host></hosts>

    <securityproperties mode="Message">
      <messagesecurity authorizationinfo="YOUR_KEY_HERE">
    </messagesecurity></securityproperties>
  </datacacheclient>
</configuration>

使用代码

完成将此 XML 添加到您的 app.config 后,您需要引用 Windows Azure AppFabric SDK v2.0 中的两个程序集,您可以此处下载。您需要的程序集位于 \Program Files\Windows Azure AppFabric SDK\V2.0\Assemblies\Cache\ 中,您需要引用 Microsoft.ApplicationServer.Caching.Core.dllMicrosoft.ApplicationServer.Caching.Client.dll

添加这两个引用将允许所有必要的方法和命名空间暴露并被您的代码使用。我们特别需要 DataCacheFactoryDataCache 类,它们包含所有必要的方法来初始化缓存客户端并与服务交互。

using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
{
     // Get a default cache client
     DataCache dataCache = dataCacheFactory.GetDefaultCache();
}

由于我们不提供任何参数,因此将初始化并由 DataCache 客户端使用从配置文件中读取的默认值。

使用 DataCache 客户端相当容易,就像任何其他分布式缓存一样。它具有将对象 Put() 到缓存中、从缓存中 Get() 对象等方法。无论您从缓存中放入或获取什么,都必须指定一个此对象唯一的键。在我们的例子中,我使用 Person 类的 FullName,它由该类的一个方法返回。

// Put that object into the cache
dataCache.Put(nPerson.GetFullName(), nPerson);

// Get the cached object back from the cache
Person cachedPerson = (Person)dataCache.Get(nPerson.GetFullName());

您可能会注意到 Person 类使用 DataContract 属性进行修饰,并且所有属性都使用 DataMember 属性进行修饰。这是必需的,以便对象可以序列化并存储到缓存中。这两个属性都存在于 System.ServiceModel 程序集中,您也必须在项目中添加对其的引用。该程序集位于 GAC 中,因为它是 .NET Framework 的一部分。

[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string Lastname { get; set; }
    [DataMember]
    private decimal Money { get; set; }

    public Person(string firstname, string lastname)
    {
        FirstName = firstname;
        Lastname = lastname;
        Money = 0;
    }

    public decimal WithdrawMoney(decimal amount)
    {
        return Money -= amount;
    }

    public void DepositMoney(decimal amount)
    {
        Money += amount;
    }

    public decimal GetBalance()
    {
        return Money; 
    }

    public string GetFullName()
    {
        return string.Format("{0} {1}", FirstName, Lastname);
    }
}

Windows Azure AppFabric Cache 还有其他方面,我将在未来的文章中探讨,例如如何仅当对象比内存中已有的版本更新时才获取它,或者如何处理缓存中多个对象的版本控制,以及如何在特定时间段后自动从缓存中删除对象。

所有代码都在 Program.cs

// DataCacheFactory will use settings from app.config
using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
{
    // Get a default cache client
    DataCache dataCache = dataCacheFactory.GetDefaultCache();

    // Create a new person
    Person nPerson = new Person("Panagiotis", "Kefalidis");
    Console.WriteLine(string.Format("Currently in your account: {0}", 
                                    nPerson.GetBalance()));

    // Deposit some money
    nPerson.DepositMoney(100);
    Console.WriteLine(string.Format("Currently in your " + 
            "account after deposit: {0}", nPerson.GetBalance()));

    // Put that object into the cache
    dataCache.Put(nPerson.GetFullName(), nPerson);

    // Remove some money
    nPerson.WithdrawMoney(50);

    // Get the cached object back from the cache
    Person cachedPerson = (Person)dataCache.Get(nPerson.GetFullName());

    // How much money do we have now?
    Console.WriteLine(string.Format("Currently in your " + 
       "cached account after withdraw: {0}", cachedPerson.GetBalance()));

    // How much money we REALLY have now?
    Console.WriteLine(string.Format("Currently in your account " + 
                      "after withdraw: {0}", nPerson.GetBalance()));

    // Update the cache with latest information
    dataCache.Put(nPerson.GetFullName(), nPerson);
}
Console.ReadKey();

关注点

您可以通过此 URL 了解更多关于缓存的信息:http://msdn.microsoft.com/en-us/library/ee790954.aspx。请注意,这指的是 Windows Server AppFabric,而不是 Windows Azure AppFabric,但它是了解更多信息和概览底层基础架构的非常好来源。

您还可以在我的博客上获取有关 Windows Azure 平台的更多信息:http://www.kefalidis.me

历史

  • 2011/02/16:第一版发布。
© . All rights reserved.