阅读 需要大约 5 分钟。
前景:
Azure Cosmos DB 由 Microsoft 提供,是全球分布式多模型数据库。 通过 Azure Cosmos DB 跨任意数量的 Azure 地理区域弹性且独立地缩放吞吐量和存储。 它通过综合服务级别协议 (SLA) 提供吞吐量、延迟、可用性和一致性保证。Azure Cosmos DB 可以轻松地生成可缩放且响应迅速的全局规模应用程序。
介绍:
多个数据模型和用于访问及查询数据的常用 API。
以上是引用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
1 2 3 4 | "DocumentDb": { "Endpoint": "https://localhost:8081", "Key":"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5WF2nQ9nDuVTqoch9b8mGGyPMbIZnqyMsEdsGQy67XIw/Jw=="} |
B > 创建Model 类,参数命名需要和appsetting.json 中的命名一样
1 2 3 4 5 | public class DocumentDbSetting { public string Endpoint { get; set; } public string Key { get; set; } } |
C > 在 startup.cs 中 添加 配置信息
1 2 3 4 5 6 7 8 | 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
1 2 3 4 5 6 7 8 | 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 简写了)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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
1 2 3 4 5 6 7 8 9 10 11 12 | 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. 不支持批量操作(插入,修改)等。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69946831/viewspace-3124303/ ,如需转载,请注明出处,否则将追究法律责任。