Azure Document DB Repository 的实现
阅读 需要大约 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 的实现的更多相关文章
- Azure Document DB 存储过程、触发器、自定义函数的实现
阅读 大约需要 4 分钟 在上一篇随笔中记录的是关于Azure Cosmos DB 中SQL API (DocumentDB) 的简介和Repository 的实现.本随笔是Document DB 中 ...
- Azure CosmosDB (10) Azure Cosmos DB体系结构
<Windows Azure Platform 系列文章目录> Azure Cosmos DB的体系结构分为以下几个部分: 1.Database Accounts Database Acc ...
- Azure Cosmos DB介绍及演示
Azure Cosmos DB 是 Microsoft 提供的全球分布式多模型数据库服务.Cosmos DB是一种NoSql数据库,但是它兼容多种API.它支持SQL, MongoDB.Cassand ...
- Azure Cosmos DB (三) EF Core 操作CURD
一,引言 接着上一篇使用 EF Core 操作 Azure CosmosDB 生成种子数据,今天我们完成通过 EF Core 实现CRUD一系列功能.EF Core 3.0 提供了CosmosDB 数 ...
- Azure Cosmos DB 使用费用参考
之前在学习Cosmos DB 中SQL API(DocumentDB) 的时候,也就是之前做的一些笔记,看到有使用费用的一些介绍,就有兴趣的去了解了下,做了一下简单的总结. 想了解更多或是购买使用的还 ...
- Azure Cosmos DB (一) 入门介绍
一,引言 今天是国庆.中秋双节房价的第三天,今天抽时间分享一篇关于使用Azure 提供的一项NoSql 服务-----Azure Cosmos DB.就有人问了,我听说过 MongoDB.Redis ...
- Azure Cosmos DB (二) SQL API 操作
一,引言 还记得国庆期间,我们学习了一下关于Azure Cosmos DB 的一些基础知识以及Azure Cosmos DB 的几种支持数据库类型.今天就开始分享一些实战操作,如何通过Azure Po ...
- Azure Cosmos DB (四) 使用EF的SQL API 异地冗余
一,引言 上一篇文章中,我们介绍到使用了EF Core 与Cosmos DB SQL API 进行结合开发.同时,大家在开发过程中一定要记得EF Core 不支持Cosmos DB 的迁移.今天我们启 ...
- Azure Cosmos DB (五) .Net Core 控制台应用
一,引言 之前在讲Azure CosmosDB Core(SQL)核心的时候,使用了EF Core 的方式,引用了 "Microsoft.EntityFrameworkCore.Cosmos ...
随机推荐
- Go语言学习笔记十: 结构体
Go语言学习笔记十: 结构体 Go语言的结构体语法和C语言类似.而结构体这个概念就类似高级语言Java中的类. 结构体定义 结构体有两个关键字type和struct,中间夹着一个结构体名称.大括号里面 ...
- 第一章 面向对象软件工程与UML
这个OOAD讲的都是很抽象的东西!老师说这个在现在的学习中用到的不是很多,但是以后出去工作的时候就会常用到的. 首先来了解OOAD是讲什么的. OOAD:Object Oriented Analysi ...
- spark报错处理
Spark报错处理 1.问题:org.apache.spark.SparkException: Exception thrown in awaitResult 分析:出现这个情况的原因是spark启动 ...
- 阿里云提示ECS服务器存在漏洞处理方法
1.阿里云提供生成修复命令,但是这个只提供给企业版,即收费的: 2.自己手动修复的话, 采用软件升级一般都可以解决.除了提示带kernel的高危漏洞的,其他的不需要重启实例即可修复. 有kernel的 ...
- Ionic3 UI组件之 PhotoViewer
PhotoViewer是常用的Cordova Plugin之一,用来显示图片. 组件特性: 根据Url显示图片 支持手势,可放大缩小 带分享按钮,可分享图片 带关闭按钮 加载错误时自动关闭组件 支持B ...
- JBoss 实战(1)
转自:https://www.cnblogs.com/aiwz/p/6154594.html JBOSS的诞生 1998年,在硅谷SUN公司的SAP实验室,一个年轻人正坐在电脑前面思考,然后写着什么东 ...
- 同一个网站下不同应用程序可以不同Framework版本
管理应用程序,高级设置,应用程序池可以改成不同的
- Winform 常用的方法
一,Winform 如何内嵌窗体 1,判断窗体中是否以还有内嵌窗体 private void ClosePreForm() { foreach (Control item in this.spCont ...
- JVM之---Java源码编译机制
Sun JDK中采用javac将Java源码编译为class文件,这个过程包含三个步骤: 1.分析和输入到符号表(Parse and Enter) Parse过程所做的工作有词法和语法分 ...
- vue + element ui 表格自定义表头,提供线上demo
前言:工作中用到 vue+element ui 的前端框架,需要使用自定义表头,需要使用 re.转载请注明出处:https://www.cnblogs.com/yuxiaole/p/9710826.h ...