3.Windows Azure Storage
Windows Azure Storage中有三种类型的存储器可用,分别是Tables、Blobs和Queues。Blob存储器可用于存放大量的非结构化的数据块。Queue存储器用于存放Web role和Worker role之间的临时消息。最后,Table存储器用于以可伸缩的方式来存放结构数据。下面的是一个总结:
切记:Table存储器跟Azure SQL根本不是一码事,或者说它跟关系数据库模型扯不上什么关系。Table存储器不是关系式的。
Azure Storage是通过REST接口进行访问的,所以任何可以建立http请求的东西都能用来访问它。这还意味着,Table存储器可以通过ADO.NET Data Services进行访问。 值得庆幸的是,Microsoft已经在其Azure SDK中建立了一个用于跟Azure Storage交互的代码包装器。到7月份的CTP为止,安装Azure SDK之后,该项目名为StorageClient,并且位于C:\Program Files\Windows Azure SDK\v1.0\Samples\StorageClient。您可以直接把这个项目添加到自己的云服务解决方案中去,或者也可以将其编译,然后在解决方案中引用它。本例中,我们将使用StorageClient接口来使用Table和Queue存储器。
4.使用Windows Azure Table存储器
开发阶段的Table存储器与Windows Azure Storage服务中的稍有不同,例如开发阶段的Table存储器要求各个表都使用固定的方案。在完整的Azure Storage服务中的Table存储器不需要对表进行配置,并且可以向同一个表中的各个实体添加不同数量和类型的属性。关于开发版和生产版的不同之处,详情请见http://msdn.microsoft.com/en- us/library/dd320275.aspx。
为了创建表的方案和用于访问表的数据的数据服务上下文,我们需要创建两个单独的类,分别称为Calculation.cs和CalculationDataServiceContext.cs。在本项目中,这两个类已经创建,并添加一个新的、指向System.Data.Services.Client的引用。然后,将下列内容添加到相应的类中。
public class Calculation : Microsoft.Samples.ServiceHosting.StorageClient.TableStorageEntity
{
// Inheriting from TableStroageEntiry predefines the 3 necessary
// properties for storing any entity in Table storage; PartitionKey,
// RowKey and TimeStamp
public Calculation()
{
// Hardcoded for this example but can be anything; best practice
// is to assign the PartitionKey based on a value that groups
// your data to optimize search performance.
PartitionKey = "TEST";
// Unique identifier with each partition
RowKey = DateTime.Now.Ticks.ToString();
}
public int ValueOne { get; set; }
public int ValueTwo { get; set; }
public int CalcValue { get; set; }
}
CalculationDataServiceContext.cs
public class CalculationDataServiceContext : TableStorageDataServiceContext
{
public CalculationDataServiceContext(StorageAccountInfo accountInfo)
: base(accountInfo)
{ }
// Properties that return IQueryable are used by VS to create a
// table in development storage named after the property. The
// schema is defined by the public properites in the model class.
public IQueryable Calculations
{
get
{
return this.CreateQuery("Calculations");
}
}
// Method to take two input values, input them into the table storage
// and returns the RowKey so the value can be later retrieved.
public sting AddCalculation(int valueOne, int valueTwo)
{
Calculation calc = new Calculation();
calc.ValueOne = valueOne;
calc.ValueTwo = valueTwo;
this.AddObject("Calculations", calc);
this.SaveChanges();
return calc.RowKey;
}
}
成功创建这两个类之后,下一步是通过visual studio创建测试存储表。在Solution Explorer中,右键单击MyCloudService项目,并选择“create test storage tables”项。 当Visual Studio完成时,它将显示一个消息。现在,我们可以对应用程序进行调试了,打开Development Storage管理窗口,然后就能看到正在运行的Table服务。
图5 创建Table之后的Development Storage管理窗口