Azure Table storage 基本用法

Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob、Queue、File 和 Table,其中的 Table 就是本文的主角 Azure Table storage。php

Azure Table storage 是一个在云端存储结构化 NoSQL 数据的服务,它不只存取速度快,并且效费比高。MSDN 上的说法是:成本显著低于传统 SQL!sql

笔者最近在项目中用 Table storage 实现了一个日志表,在此和你们分享一下 Table storage 的基本用法。测试

文章来源:葡萄城产品技术社区this

Azure storage account

首先须要说明,对 Blob、Queue、File 和 Table 这些 Azure 提供的存储服务的访问控制都是经过 storage account 来进行的,因此要想使用 Table storage,须要先建立你的 storage account。spa

具体建立过程,MSDN 上有详细讲解。你须要了解一下 Access keys,由于它就是你访问 storage account 的用户名和密码:设计

1

建立Table storage的对象

在使用 Azure Table storage 的相关对象前,咱们须要安装对应的包。安装过程其实很简单,只需在 Visual Studi o的 Package Manager Console 中输入:日志

Install-Package WindowsAzure.Storage

Visual Studio 就会自动安装 WindowsAzure.Storage 包及其依赖的全部包,安装完成后的 packages.config 文件看起来像这个样子:cdn

2

安装完相关的包之后,咱们就可使用其中的类型了。对象

CloudStorageAccount 类表示一个 Azure storage account,咱们须要先建立它的实例,才能访问属于它的资源。blog

//注意链接字符串中的xxx和yyy,分别对应Access keys中的Storage account name 和 key。
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=yyy");

CloudTableClient 类是 Windows Azure Table Service 客户端的逻辑表示,咱们须要使用它来配置和执行对 Table storage 的操做。

CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient();

CloudTable 类表示一张数据表。

咱们须要建立一个实例去引用 Table storage 中的一张表,测试用的表名叫”MyLogTable”。

CloudTable logTable = cloudTableClient.GetTableReference("MyLogTable");
// 若是不肯定表是否被建立过,能够调用CreateIfNotExists方法。
logTable.CreateIfNotExists();

这样在后面的操做中就能够确保 MyLogTable 表是存在的,有了 logTable 对象咱们就能够向表中插入数据了。

可是等等,好像少了点什么。

咱们开篇第一句中就说明了,Table storage 存储的是结构化的数据,因此咱们还要先定义存储的数据的类型。

定义日志类

在定义咱们本身的数据类型时,有一个强制性的要求,必须继承自 TableEntity 类型:

复制代码

{
    public MyLogEntity() { }
    public MyLogEntity(string pkey, string rkey)
    {
        this.PartitionKey = pkey;
        this.RowKey = rkey;
    }

    public DateTime LogDate { get; set; }
    public string LogMessage { get; set; }
    public string ErrorType { get; set; }
}

复制代码

在咱们的设计中,PartitionKey 用来存放产生日志的年份和月份(例如 201607),RowKey 用来存放产生日志的天和时分秒毫秒(例如 160934248492),日志数据主要是 LogDate, LogMessage 和 ErrorType。

把数据插入到Table storage

终于能够向表中插入数据了,先试一下:

复制代码

DateTime now = DateTime.Now;
string partitionKey = now.ToString("yyyyMM");
string rowKey = now.ToString("ddHHmmssffff");
MyLogEntity logEntity = new MyLogEntity(partitionKey, rowKey);
logEntity.LogDate = now;
logEntity.LogMessage = "test message";
logEntity.ErrorType = "error";
// TableOperation类表示对一个表进行的操做,能够插入一行或多行数据,删除数据,更新数据等。
TableOperation insertOperation = TableOperation.Insert(logEntity);
logTable.Execute(insertOperation);

复制代码

看起来还不错,咱们用 Visual Studio 自带的 Cloud Explorer 查看一下 MyLogTable 中的内容:

3

OK,数据已经成功插入到 MyLogTable 表中,接下来咱们看看如何批量的插入数据。

复制代码

TableBatchOperation batchOperation = new TableBatchOperation();
for (int i = 0; i < 10; i++)
{
    DateTime now = DateTime.Now;
    string partitionKey = now.ToString("yyyyMM");
    string rowKey = now.ToString("ddHHmmssffff");
    MyLogEntity logEntity = new MyLogEntity(partitionKey, rowKey);
    logEntity.LogDate = now;
    logEntity.LogMessage = "test message" + i.ToString();
    logEntity.ErrorType = (i%2) == 0 ? "error" : "warning";
    batchOperation.Insert(logEntity);
    Thread.Sleep(10);
}
logTable.ExecuteBatch(batchOperation);

复制代码

此次咱们把 TableOperation 类换成了 TableBatchOperation 类,而后一次插入十条数据。去检查一下结果,OK十条数据所有插入成功!

下面让咱们把循环中的10改为200试试:

4

怎么收到一个 InvalidOperationException 呢?看看红框中的内容,原来批量操做是有一些限制的:

1. 每一个批量操做的数据上限是100条记录。

2. 每一个批量操做中的数据都必须保持相同的 partition key。

请你们在使用批量操做时务必注意这些限制条件!

查询操做

对于日志数据的操做,最重要的就是查询,咱们经过几个具体的用例来介绍 Table storage 的查询操做。

1. 查询全部的记录

这是最简单的查询方法,通常是想要导出所有数据时才会这么干:

TableQuery<MyLogEntity> query = new TableQuery<MyLogEntity>();
foreach (MyLogEntity entity in logTable.ExecuteQuery(query))
{
    Console.WriteLine("{0}\t{1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey, entity.LogMessage, entity.ErrorType);
}

2.查询某年的某个月的记录

要查询某个月的全部记录也是比较容易的,由于咱们设计的 PartitionKey 就表明了某个月份:

复制代码

TableQuery<MyLogEntity> query = new TableQuery<MyLogEntity>().Where(
    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "201607"));
foreach (MyLogEntity entity in logTable.ExecuteQuery(query))
{
    //...
}

复制代码

请注意 TableQuery.GenerateFilterCondition 方法,咱们建立了一个过滤条件:PartitionKey 等于“201607”。这个查询会把全部 PartitionKey 为“201607”的记录都找到!

3.查询某一条记录

若是咱们已经知道了一条记录的 PartitionKey 和 RowKey,就能够经过这两个条件直接查询到这条记录的详情:

复制代码

TableQuery<MyLogEntity> query = new TableQuery<MyLogEntity>().Where(
    TableQuery.CombineFilters(
        TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "201607"),
        TableOperators.And,
        TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, "161148372454")));
foreach (MyLogEntity entity in logTable.ExecuteQuery(query))
{
    //...
}

复制代码

此次咱们使用了组合条件,只用到了条件运算操做 TableOperators.And 和 QueryComparisons.Equal,固然你也能够尝试其它的条件类型。惟一要注意的就是: PartitionKey 和 RowKey,QueryComparisons 的操做对象都是字符串。

咱们还须要更多的查询条件,好比查询某一天产生的全部日志。在 MyLogTable 表中,这须要查询以”xx”字符串开头的 RowKey。这部分知识,我会单独在一篇文章中和你们分享相关内容,由于它并不像看起来的那么简单。

接下来咱们介绍如何更新和删除日志表中的数据,这里只是借用日志表介绍更新和删除操做。

更新记录

复制代码

TableOperation retrieveOperation = TableOperation.Retrieve<MyLogEntity>("201607", "161148372454");
TableResult retrievedResult = logTable.Execute(retrieveOperation);
MyLogEntity updateEntity = (MyLogEntity)retrievedResult.Result;

if (updateEntity != null)
{
    updateEntity.LogMessage = "new log message";
    TableOperation updateOperation = TableOperation.Replace(updateEntity);
    logTable.Execute(updateOperation);
}

复制代码

以上操做,咱们先用 TableOperation.Retrieve 方法得到一条数据的详情,而后更新它的 LogMessage 属性,最后使用 TableOperation.Replace 方法把新的内容更新的到 Table storage 中。

删除记录

删除一条记录和更新一条记录是基本同样的步骤,不一样点是把 TableOperation.Replace 方法换成 TableOperation.Delete 方法:

复制代码

TableOperation retrieveOperation = TableOperation.Retrieve<MyLogEntity>("201607", "161148372454");
TableResult retrievedResult = logTable.Execute(retrieveOperation);
MyLogEntity deleteEntity = (MyLogEntity)retrievedResult.Result;
if (deleteEntity != null)
{
    TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
    logTable.Execute(deleteOperation);
}

复制代码

删除表

删除表和建立表同样简单(可比删除一条记录容易多了):

logTable.DeleteIfExists();

总结,本文经过对一个日志表的操做介绍了 Azure Table storage 的一个典型应用场景和基本的使用方法,从操做的代码上看和传统的 sql 表操做差异仍是挺大的。但愿本文对朋友们了解 Azure Table storage 能有所帮助。

相关文章
相关标签/搜索