閱讀 須要大約 5 分鐘。html
前景:sql
Azure Cosmos DB 由 Microsoft 提供,是全球分佈式多模型數據庫。 經過 Azure Cosmos DB 跨任意數量的 Azure 地理區域彈性且獨立地縮放吞吐量和存儲。 它經過綜合服務級別協議 (SLA) 提供吞吐量、延遲、可用性和一致性保證。Azure Cosmos DB 能夠輕鬆地生成可縮放且響應迅速的全局規模應用程序。mongodb
介紹:數據庫
多個數據模型和用於訪問及查詢數據的經常使用 API。apache
以上是引用Microsoft 官網中文文檔,地址:https://docs.microsoft.com/zh-cn/azure/cosmos-db/introduction。json
Azure Cosmos DB 是Microsoft 推出的雲服務數據庫,提供多種API 服務,如下主要講的是SQL API,以json 形式的文檔數據庫。api
Step 1: 配置環境(使用的是.net core 解決方案)架構
A > 在appsetting.json 中添加 AccountEndpoint 和 AccountKeyapp
"DocumentDb": { "Endpoint": "https://localhost:8081", "Key":"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5WF2nQ9nDuVTqoch9b8mGGyPMbIZnqyMsEdsGQy67XIw/Jw==" }
B > 建立Model 類,參數命名須要和appsetting.json 中的命名同樣async
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