教程:使用 Xamarin 和 Azure Cosmos DB 生成移动应用程序Tutorial: Build mobile applications with Xamarin and Azure Cosmos DB

大多数移动应用需要在云中存储数据,而 Azure Cosmos DB 正是适用于移动应用的云数据库。Most mobile apps need to store data in the cloud, and Azure Cosmos DB is a cloud database for mobile apps. 该产品提供移动开发人员所需的一切功能。It has everything a mobile developer needs. 它是一个完全托管的数据库即服务,可按需缩放。It is a fully managed database as a service that scales on demand. 无论用户位于中国各地的何处,它都可以透明地将数据传输到应用程序。It can bring your data to your application transparently, wherever your users are located around China. 使用 Azure Cosmos DB .NET Core SDK,可让 Xamarin 移动应用直接与 Azure Cosmos DB 交互,无需中间层。By using the Azure Cosmos DB .NET Core SDK, you can enable Xamarin mobile apps to interact directly with Azure Cosmos DB, without a middle tier.

本文提供有关使用 Xamarin 和 Azure Cosmos DB 生成移动应用的教程。This article provides a tutorial for building mobile apps with Xamarin and Azure Cosmos DB. 可在 GitHub 上的 Xamarin 和 Azure Cosmos DB 中找到本教程的完整源代码,其中包括如何管理用户和权限。You can find the complete source code for the tutorial at Xamarin and Azure Cosmos DB on GitHub, including how to manage users and permissions.

移动应用的 Azure Cosmos DB 功能Azure Cosmos DB capabilities for mobile apps

Azure Cosmos DB 为移动应用开发人员提供以下重要功能:Azure Cosmos DB provides the following key capabilities for mobile app developers:

移动应用的 Azure Cosmos DB 功能

  • 针对无架构数据的丰富查询。Rich queries over schemaless data. Azure Cosmos DB 将数据以无架构 JSON 文档的形式存储在异构集合中。Azure Cosmos DB stores data as schemaless JSON documents in heterogeneous collections. 它提供丰富的快速查询,无需担心架构或索引问题。It offers rich and fast queries without the need to worry about schemas or indexes.
  • 快速吞吐量。Fast throughput. 使用 Azure Cosmos DB 时,只需几毫秒就能读取和写入文档。It takes only a few milliseconds to read and write documents with Azure Cosmos DB. 开发人员可以指定所需的吞吐量,Azure Cosmos DB 对所有单区域帐户和具有松散一致性的所有多区域帐户采用 99.99% 的可用性 SLA,对所有多区域数据库帐户采用 99.999% 的读取可用性。Developers can specify the throughput they need, and Azure Cosmos DB honors it with 99.99% availability SLA for all single region accounts and all multi-region accounts with relaxed consistency, and 99.999% read availability on all multi-region database accounts.
  • 无限规模。Limitless scale. Azure Cosmos 容器随着应用的增长而增长Your Azure Cosmos containers grow as your app grows. 一开始可以处理较小规模的数据和每秒几百个请求的吞吐量。You can start with small data size and throughput of hundreds of requests per second. 集合或数据库可以增长到 PB 量级的数据和每秒几亿个请求的任意大的吞吐量。Your collections or databases can grow to petabytes of data and arbitrarily large throughput with hundreds of millions of requests per second.
  • 多区域分布式。Multiple-regionally distributed. 移动应用用户的特点是经常在中国不同的地点漫游。Mobile app users are on the go, often across China. Azure Cosmos DB 是多区域分布式数据库Azure Cosmos DB is a multiple-regionally distributed database. 单击地图即可让用户访问数据。Click the map to make your data accessible to your users.
  • 内置丰富授权。Built-in rich authorization. 有了 Azure Cosmos DB,无需使用复杂的自定义授权代码,就能轻松实现常用的模式,例如,每个用户的数据,或者多个共享用户的数据。With Azure Cosmos DB, you can easily implement popular patterns like per-user data or multiuser shared data, without complex custom authorization code.
  • 地理空间查询。Geospatial queries. 许多移动应用现在可以提供区分地理环境的体验。Many mobile apps offer geo-contextual experiences today. 凭借对地理空间类型的一流支持,Azure Cosmos DB 可轻松创建这些体验。With first-class support for geospatial types, Azure Cosmos DB makes creating these experiences easy to accomplish.
  • 二进制附件。Binary attachments. 应用数据通常包含二进制 Blob。Your app data often includes binary blobs. Azure Cosmos DB 原生支持附件,因此可以更轻松地用作应用数据的一站式存储库。Native support for attachments makes it easier to use Azure Cosmos DB as a one-stop shop for your app data.

Azure Cosmos DB 和 Xamarin 教程Azure Cosmos DB and Xamarin tutorial

以下教程介绍如何使用 Xamarin 和 Azure Cosmos DB 生成移动应用程序。The following tutorial shows how to build a mobile application by using Xamarin and Azure Cosmos DB. 可在 GitHub 上的 Xamarin 和 Azure Cosmos DB 中找到该教程的完整源代码。You can find the complete source code for the tutorial at Xamarin and Azure Cosmos DB on GitHub.

入门Get started

Azure Cosmos DB 入门容易。It's easy to get started with Azure Cosmos DB. 转到 Azure 门户,并创建新的 Azure Cosmos DB 帐户。Go to the Azure portal, and create a new Azure Cosmos DB account. 单击“快速入门”选项卡。 下载已连接到 Azure Cosmos DB 帐户的 Xamarin Forms 待办事项列表示例。Click the Quick start tab. Download the Xamarin Forms to-do list sample that is already connected to your Azure Cosmos DB account.

适用于移动应用的 Azure Cosmos DB 快速入门

或者,如果已有一个 Xamarin 应用,则可以添加 Azure Cosmos DB NuGet 包Or if you have an existing Xamarin app, you can add the Azure Cosmos DB NuGet package. Azure Cosmos DB 支持 Xamarin.IOS、Xamarin.Android 和 Xamarin Forms 共享库。Azure Cosmos DB supports Xamarin.IOS, Xamarin.Android, and Xamarin Forms shared libraries.

处理数据Work with data

数据记录以无架构 JSON 文档的形式存储在 Azure Cosmos DB 的异构集合中。Your data records are stored in Azure Cosmos DB as schemaless JSON documents in heterogeneous collections. 可在同一个集合中存储具有不同结构的文档:You can store documents with different structures in the same collection:

    var result = await client.CreateDocumentAsync(collectionLink, todoItem);

在 Xamarin 项目中,可以针对无架构数据使用语言集成的查询:In your Xamarin projects, you can use language-integrated queries over schemaless data:

    var query = await client.CreateDocumentQuery<ToDoItem>(collectionLink)
                    .Where(todoItem => todoItem.Complete == false)
                    .AsDocumentQuery();

    Items = new List<TodoItem>();
    while (query.HasMoreResults) {
        Items.AddRange(await query.ExecuteNextAsync<TodoItem>());
    }

添加用户Add users

与许多入门示例一样,下载的 Azure Cosmos DB 示例使用已在应用代码中硬编码的主密钥向服务进行身份验证。Like many get started samples, the Azure Cosmos DB sample you downloaded authenticates to the service by using a master key hardcoded in the app's code. 除非在本地模拟器上运行应用,否则这种默认行为不是最佳做法。This default is not a good practice for an app you intend to run anywhere except on your local emulator. 如果未经授权的用户获取了主密钥,整个 Azure Cosmos DB 帐户中的所有数据可能会泄露。If an unauthorized user obtained the master key, all the data across your Azure Cosmos DB account could be compromised. 应用最好是只能访问已登录用户的记录。Instead, you want your app to access only the records for the signed-in user. Azure Cosmos DB 允许开发人员向应用程序授予对某个集合、按分区键分组的一组文档或某个特定文档的读取或读/写权限。Azure Cosmos DB allows developers to grant application read or read/write permission to a collection, a set of documents grouped by a partition key, or a specific document.

遵循以下步骤将待办事项列表应用修改为多用户待办事项列表应用:Follow these steps to modify the to-do list app to a multiuser to-do list app:

  1. 使用 Facebook、Active Directory 或其他任何提供程序将登录名添加到应用。Add Login to your app by using Facebook, Active Directory, or any other provider.

  2. 创建使用 /userId 作为分区键的 Azure Cosmos DB UserItems 集合。Create an Azure Cosmos DB UserItems collection with /userId as the partition key. 为集合指定分区键可让 Azure Cosmos DB 随着应用用户的增多而无限缩放,同时可持续提供快速查询。Specifying the partition key for your collection allows Azure Cosmos DB to scale infinitely as the number of your app users grows, while continuing to offer fast queries.

  3. 添加 Azure Cosmos DB 资源令牌代理。Add Azure Cosmos DB Resource Token Broker. 这是一个简单的 Web API,可对用户进行身份验证,并向只有权访问其自己分区中的文档的已登录用户颁发短期生存的令牌。This simple Web API authenticates users and issues short-lived tokens to signed-in users with access only to the documents within their partition. 在此示例中,资源令牌代理托管在应用服务中。In this example, Resource Token Broker is hosted in App Service.

  4. 将应用修改为使用 Facebook 对资源令牌代理进行身份验证,请求已登录的 Facebook 用户的资源令牌。Modify the app to authenticate to Resource Token Broker with Facebook, and request the resource tokens for the signed-in Facebook users. 然后,可在 UserItems 集合中访问其数据。You can then access their data in the UserItems collection.

可在 GitHub 上的资源令牌代理中找到此模式的完整代码示例。You can find a complete code sample of this pattern at Resource Token Broker on GitHub. 下图演示了该解决方案:This diagram illustrates the solution:

Azure Cosmos DB 用户和权限代理

如果希望两个用户能够访问同一个“待办事项列表”,可将其他权限添加到资源令牌代理中的访问令牌。If you want two users to have access to the same to-do list, you can add additional permissions to the access token in Resource Token Broker.

按需缩放Scale on demand

Azure Cosmos DB 是托管型数据库即服务。Azure Cosmos DB is a managed database as a service. 随着用户群体的扩大,不用担心是否要预配 VM 或增加核心,As your user base grows, you don't need to worry about provisioning VMs or increasing cores. 只需告诉 Azure Cosmos DB 应用所需的每秒操作次数(吞吐量)。All you need to tell Azure Cosmos DB is how many operations per second (throughput) your app needs. 可以通过“缩放”选项卡,使用一个名为每秒请求单位数 (RU) 的吞吐量度量值来指定吞吐量。 You can specify the throughput via the Scale tab by using a measure of throughput called Request Units (RUs) per second. 例如,针对 1-KB 文档执行一次读取操作需要 1 个 RU。For example, a read operation on a 1-KB document requires 1 RU. 还可以针对吞吐量指标添加警报,用于监视流量的增长以及在警报触发时以编程方式更改吞吐量。You can also add alerts to the Throughput metric to monitor the traffic growth and programmatically change the throughput as alerts fire.

Azure Cosmos DB 可按需缩放吞吐量

达到多区域规模Go multiple-region scale

在应用受到广泛欢迎后,可以吸收中国的用户。As your app gains popularity, you might gain users across China. 或许需要针对一些不可预见的事件做好准备。Or maybe you want to be prepared for unforeseen events. 转到 Azure 门户,并打开 Azure Cosmos DB 帐户。Go to the Azure portal, and open your Azure Cosmos DB account. 单击地图即可将数据持续复制到中国任意数目的区域。Click the map to make your data continuously replicate to any number of regions across China. 此功能可向任意位置的用户提供数据。This capability makes your data available wherever your users are. 还可以添加故障转移策略,针对意外状况做好准备。You can also add failover policies to be prepared for contingencies.

Azure Cosmos DB 可跨地理区域缩放

祝贺。Congratulations. 现已完成本解决方案,并使用 Xamarin 和 Azure Cosmos DB 生成了一个移动应用。You have completed the solution and have a mobile app with Xamarin and Azure Cosmos DB. 按照类似的步骤,使用 Azure Cosmos DB JavaScript SDK 生成 Cordova 应用,使用 Azure Cosmos DB REST API 生成本机 iOS/Android 应用。Follow similar steps to build Cordova apps by using the Azure Cosmos DB JavaScript SDK and native iOS/Android apps by using Azure Cosmos DB REST APIs.

后续步骤Next steps