阅读 需要大约  5 分钟。

前景:

  Azure Cosmos DB 由 Microsoft 提供,是全球分布式多模型数据库。 通过 Azure Cosmos DB 跨任意数量的 Azure 地理区域弹性且独立地缩放吞吐量和存储。 它通过综合服务级别协议 (SLA) 提供吞吐量、延迟、可用性和一致性保证。Azure Cosmos DB 可以轻松地生成可缩放且响应迅速的全局规模应用程序。

介绍:

  多个数据模型和用于访问及查询数据的常用 API。

  • Azure Cosmos DB 本身所基于的数据模型以 Atom 记录序列 (ARS) 为基础,该模型支持多个数据模型,包括但不限于文档、图形、键-值、表以及列系列数据模型。
  • 多种语言的 SDK 均支持以下数据模型的 API:
    • SQL API:具有丰富 SQL 查询功能的无架构 JSON 数据库引擎。
    • MongoDB API:一种可大规模缩放的服务型 MongoDB,由 Azure Cosmos DB 平台提供支持。 与现有 MongoDB 库、驱动程序、工具和应用程序兼容。
    • Cassandra API:一种可全局分发的服务型 Cassandra,由 Azure Cosmos DB 平台提供支持。 与现有Apache Cassandra 库、驱动程序、工具和应用程序兼容。
    • Gremlin API:一种完全托管的、可横向缩放的图形数据库服务,可以轻松地用于生成和运行特定的应用程序,这些应用程序适用于支持开放式 Gremlin API(基于 Apache TinkerPop 规范:Apache Gremlin)的高度连接数据集。
    • 表 API:一种键值对型数据库服务,可以在不进行任何应用更改的情况下,为现有的 Azure 表存储应用程序提供高级功能(例如,自动索引、低延迟保证、全局分发)

以上是引用Microsoft 官网中文文档,地址:https://docs.microsoft.com/zh-cn/azure/cosmos-db/introduction。

Azure Cosmos DB 是Microsoft 推出的云服务数据库,提供多种API 服务,以下主要讲的是SQL API,以json 形式的文档数据库。

Step 1: 配置环境(使用的是.net core 解决方案)

A > 在appsetting.json 中添加 AccountEndpoint 和 AccountKey

"DocumentDb": {
  "Endpoint": "https://localhost:8081",
  "Key":"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5WF2nQ9nDuVTqoch9b8mGGyPMbIZnqyMsEdsGQy67XIw/Jw=="
}

  

B > 创建Model 类,参数命名需要和appsetting.json 中的命名一样

public class DocumentDbSetting
{
public string Endpoint { get; set; }
public string Key { get; set; }
}

C > 在 startup.cs 中 添加 配置信息

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // 添加的配置
var documentDbSection = Configuration.GetSection("DocumentDb");
services.Configure<DocumentDbSetting>(documentDbSection);
}

D > 创建DocumentDbRepository,获取appsetting.json 中的endpoint 和 key,构造client

private readonly Lazy<IDocumentClient> _client;
public DocumentDbRepository(IOptions<DocumentDbSetting> documentDbSetting)
{
var uri = new Uri(documentDbSetting.Value.Endpoint);
var documentClient = new DocumentClient(uri, documentDbSetting.Value.Key); _client = new Lazy<IDocumentClient>(() => documentClient, true);
}

Step 2: 增删改查的实现

A >  create document(databaseName 指数据库名,collectionName 指的是文档名(相当于表的名称),document 就是存储的一条记录)(以下代码中catch exception 简写了)

public async Task<bool> CreateDocumentAsync<T>(string databaseName, string collectionName, T document) where T : class
{
try
{
await CreateDocumentCollectionAsync(collectionName, databaseName);
var uri = UriFactory.CreateDocumentCollectionUri(databaseName, collectionName); var response = await _client.Value.CreateDocumentAsync(uri, document); bool result = (response != null && (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK)); return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

  在创建数据时,需要验证database和collection 是否存在,当不存在时,会创建的对应的database和collection。

protected async Task<bool> CreateDatabaseAsync(string databaseName)
{
var db = await _client.Value.CreateDatabaseIfNotExistsAsync(new DocDatabase { Id = databaseName }); return db.StatusCode == HttpStatusCode.Created || db.StatusCode == HttpStatusCode.OK;
} protected async Task<bool> CreateDocumentCollectionAsync(string collectionName, string databaseName)
{
if (string.IsNullOrWhiteSpace(databaseName))
{
throw new ArgumentNullException(nameof(databaseName));
} if (await CreateDatabaseAsync(databaseName))
{
var result = await _client.Value.CreateDocumentCollectionIfNotExistsAsync(
UriFactory.CreateDatabaseUri(databaseName), new DocumentCollection
{
Id = collectionName,
IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 })
}); return result.StatusCode == HttpStatusCode.Created || result.StatusCode == HttpStatusCode.OK;
} return false;
}

B > 修改document有两种方式Upsert 和Replace,Upsert 的特点是 当没有这条数据时,会创建一条,而Replace 会报异常。

Upsert Document

public async Task<bool> UpdateDocumentAsync<T>(string databaseName, string collectionName, T document) where T : class
{
try
{
var uri = UriFactory.CreateDocumentCollectionUri(databaseName, collectionName);
var result = await _client.Value.UpsertDocumentAsync(uri, document); return result.StatusCode == HttpStatusCode.OK || result.StatusCode == HttpStatusCode.Created;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Replace Document

public async Task<bool> ReplaceDocumentAsync<T>(string databaseName, string collectionName, T document, string id) where T : class
{
try
{
var uri = UriFactory.CreateDocumentUri(databaseName, collectionName, id);
var result = await _client.Value.ReplaceDocumentAsync(uri, document); return result.StatusCode == HttpStatusCode.OK;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

C > Get Document

根据Id获取Document

public async Task<T> GetDocument<T>(string databaseName, string collectionName, string id, FeedOptions feedOptions = null) where T : class
{
try
{
Document document = await _client.Value.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, id)); return (T)(dynamic)document;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

根据条件获取Documents

public async Task<IEnumerable<T>> GetQueryable<T>(string databaseName, string collectionName, Expression<Func<T, bool>> predicate, FeedOptions feedOptions = null) where T : new()
{
var dummy = new T(); IDocumentQuery<T> query = _client.Value.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), feedOptions)
.Where(predicate)
.AsDocumentQuery(); var results = new List<T>(); while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<T>());
} return results;
}

D > Delete Document

public async Task<bool> DeleteDocumentAsync(string databaseName, string collectionName, string documentId)
{
try
{
var documentResponse = await _client.Value.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, documentId));
return documentResponse.StatusCode == HttpStatusCode.NoContent;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}  

本地测试开发使用工具:

Azure Cosmos DB Emulator. 下载地址https://aka.ms/cosmosdb-emulator  ,使用方法

Microsoft Azure Storage Explorer 是存储资源管理器 下载地址https://azure.microsoft.com/en-us/features/storage-explorer/ ,使用方法


在当前的版本中  1. 不支持skip 分页 和group by 分组。 2. 不支持批量操作(插入,修改)等。

 以上只是本人学习笔记分享!有许多不足之处,还在继续添加和更正。本随笔链接:https://www.cnblogs.com/OneManStep/p/10161565.html

Azure Document DB Repository 的实现的更多相关文章

  1. Azure Document DB 存储过程、触发器、自定义函数的实现

    阅读 大约需要 4 分钟 在上一篇随笔中记录的是关于Azure Cosmos DB 中SQL API (DocumentDB) 的简介和Repository 的实现.本随笔是Document DB 中 ...

  2. Azure CosmosDB (10) Azure Cosmos DB体系结构

    <Windows Azure Platform 系列文章目录> Azure Cosmos DB的体系结构分为以下几个部分: 1.Database Accounts Database Acc ...

  3. Azure Cosmos DB介绍及演示

    Azure Cosmos DB 是 Microsoft 提供的全球分布式多模型数据库服务.Cosmos DB是一种NoSql数据库,但是它兼容多种API.它支持SQL, MongoDB.Cassand ...

  4. Azure Cosmos DB (三) EF Core 操作CURD

    一,引言 接着上一篇使用 EF Core 操作 Azure CosmosDB 生成种子数据,今天我们完成通过 EF Core 实现CRUD一系列功能.EF Core 3.0 提供了CosmosDB 数 ...

  5. Azure Cosmos DB 使用费用参考

    之前在学习Cosmos DB 中SQL API(DocumentDB) 的时候,也就是之前做的一些笔记,看到有使用费用的一些介绍,就有兴趣的去了解了下,做了一下简单的总结. 想了解更多或是购买使用的还 ...

  6. Azure Cosmos DB (一) 入门介绍

    一,引言 今天是国庆.中秋双节房价的第三天,今天抽时间分享一篇关于使用Azure 提供的一项NoSql 服务-----Azure Cosmos DB.就有人问了,我听说过 MongoDB.Redis ...

  7. Azure Cosmos DB (二) SQL API 操作

    一,引言 还记得国庆期间,我们学习了一下关于Azure Cosmos DB 的一些基础知识以及Azure Cosmos DB 的几种支持数据库类型.今天就开始分享一些实战操作,如何通过Azure Po ...

  8. Azure Cosmos DB (四) 使用EF的SQL API 异地冗余

    一,引言 上一篇文章中,我们介绍到使用了EF Core 与Cosmos DB SQL API 进行结合开发.同时,大家在开发过程中一定要记得EF Core 不支持Cosmos DB 的迁移.今天我们启 ...

  9. Azure Cosmos DB (五) .Net Core 控制台应用

    一,引言 之前在讲Azure CosmosDB Core(SQL)核心的时候,使用了EF Core 的方式,引用了 "Microsoft.EntityFrameworkCore.Cosmos ...

随机推荐

  1. epoll—IO多路复用

    1.在socket.listen()后创一个epoll对象   epoll = select.epoll() 2.将server_socket注册到epoll中        epoll.regist ...

  2. 【Express系列】第3篇——接入mysql

    通常来说,前后端分离的项目,前端负责界面渲染和操作型的业务逻辑,后端则负责数据存取和数据处理相关的业务逻辑. 既然设计数据,那就少不了数据库的使用.目前市面上流行着各种各样的数据库,这里不打算一一列举 ...

  3. Leetcode 647. Palindromic Substrings

    Given a string, your task is to count how many palindromic substrings in this string. The substrings ...

  4. juqery dragsort使用遇到的问题

    1.destroy时,没给容器加id,不能执行成功--->修改源码如下: if (options == "destroy") { $(this).trigger(" ...

  5. ruby + phantomjs 自动化测试 - GA

    说起测试GA,真是一件枯燥乏味,重复性很高的工作,那么为什么我们不使用自动化测试代替它呢,显然,很多公司的产品迭代太快,ga也变化的比较频繁,但是确保ga工作正常,对于其他部门的工作是有很大帮助的,由 ...

  6. SpringBoot相关配置

    8.1 配置 Spring MVC的配置是通过继承WebMvcConfigurerAdapter类并重载其方法实现的; 前几个教程已做了得配置包括 01点睛Spring MVC 4.1-搭建环境 配置 ...

  7. [转]Using TRY...CATCH in Transact-SQL

    本文转自:https://technet.microsoft.com/en-us/library/ms179296(v=sql.105).aspx Using TRY...CATCH in Trans ...

  8. c#Image.FromFile图形加载异常处理

    public void UpdateImg(string picpath) { //更新至控件中 PnlImageShow.BackgroundImage = LoadImgPath(picpath) ...

  9. git 拉取远程分支报错(fatal: '' is not a commit and a branch '' cannot be created from it)

    问题描述从远程git上拉取某一个分支,然后报错,拉取不了这个分支. 拉取分支的命令: git checkout -b xxx-static-19 origin/xxx-static-19 其中xxx- ...

  10. 地址解析协议ARP,网络层协议IP、ICMP协议

    分析所用软件下载:Wireshark-win32-1.10.2.exe 阅读导览 1. 分析并且应用ARP协议 2.分析IP协议 3.分析ICMP协议 1.分析arp报文的格式与内容 (1)ping ...