教程:使用 SQL API 设置 Azure Cosmos DB 多区域分发Tutorial: Set up Azure Cosmos DB multiple-region distribution using the SQL API

适用于: SQL API

本文介绍如何使用 Azure 门户设置 Azure Cosmos DB 多区域分发,然后使用 SQL API 进行连接。In this article, we show how to use the Azure portal to set up Azure Cosmos DB multiple-region distribution and then connect using the SQL API.

本文涵盖以下任务:This article covers the following tasks:

  • 使用 Azure 门户配置多区域分发Configure multiple-region distribution using the Azure portal
  • 使用 SQL API 配置多区域分发Configure multiple-region distribution using the SQL APIs

有关 Azure Cosmos DB 中多区域数据库复制工作原理的详细信息,请参阅使用 Cosmos DB 全局分发数据For more information about how multiple-region database replication works in Azure Cosmos DB, see Distribute data globally with Cosmos DB.

使用 Azure 门户添加全局数据库区域Add global database regions using the Azure portal

在中国的所有 Azure 区域中都可使用 Azure Cosmos DB。Azure Cosmos DB is available in all Azure regions across china. 为数据库帐户选择默认的一致性级别后,可以关联一个或多个区域(具体取决于所选的默认一致性级别和多区域分发需求)。After selecting the default consistency level for your database account, you can associate one or more regions (depending on your choice of default consistency level and multiple-region distribution needs).

  1. Azure 门户的左侧栏中,单击“Azure Cosmos DB” 。In the Azure portal, in the left bar, click Azure Cosmos DB.

  2. 在“Azure Cosmos DB” 页中,选择要修改的数据库帐户。In the Azure Cosmos DB page, select the database account to modify.

  3. 在“帐户”页上的菜单中单击“全局复制数据” 。In the account page, click Replicate data globally from the menu.

  4. 在“全局复制数据” 页中,通过单击地图中的区域选择要添加或删除的区域,并单击“保存” 。In the Replicate data globally page, select the regions to add or remove by clicking regions in the map, and then click Save. 添加区域会产生费用,有关详细信息,请参阅定价页使用 Azure Cosmos DB 全局分发数据There is a cost to adding regions, see the pricing page or the Distribute data globally with Azure Cosmos DB article for more information.

    单击图中的区域可以添加或删除区域

添加第二个区域后,门户中的“全局复制数据”页上会启用“手动故障转移”选项。Once you add a second region, the Manual Failover option is enabled on the Replicate data globally page in the portal. 可以使用此选项测试故障转移过程或更改主写入区域。You can use this option to test the failover process or change the primary write region. 添加第三个区域后,会在同一页上启用“故障转移优先级” 选项,以便更改读取的故障转移顺序。Once you add a third region, the Failover Priorities option is enabled on the same page so that you can change the failover order for reads.

选择全局数据库区域Selecting global database regions

配置两个或更多区域有两个常见方案:There are two common scenarios for configuring two or more regions:

  1. 向最终用户提供对数据的低延迟访问,而无论用户位于全球范围内的何位置Delivering low-latency access to data to end users no matter where they are located around the globe
  2. 添加区域复原以实现业务连续性和灾难恢复 (BCDR)Adding regional resiliency for business continuity and disaster recovery (BCDR)

若要向最终用户提供低延迟,建议在与应用程序用户所在位置对应的区域中同时部署应用程序和 Azure Cosmos DB。For delivering low-latency to end users, it is recommended that you deploy both the application and Azure Cosmos DB in the regions that correspond to where the application's users are located.

使用 SQL API 连接到首选区域Connecting to a preferred region using the SQL API

为了利用多区域分发,客户端应用程序可以指定要用于执行文档操作的区域优先顺序列表。In order to take advantage of multiple-region distribution, client applications can specify the ordered preference list of regions to be used to perform document operations. SQL SDK 会根据 Azure Cosmos DB 帐户配置、当前区域可用性和指定的优先顺序列表,选择最佳的终结点来执行写入和读取操作。Based on the Azure Cosmos DB account configuration, current regional availability and the preference list specified, the most optimal endpoint will be chosen by the SQL SDK to perform write and read operations.

此优先顺序列表是在使用 SQL SDK 初始化连接时指定的。This preference list is specified when initializing a connection using the SQL SDKs. SDK 接受可选参数 PreferredLocations,这是 Azure 区域的顺序列表。The SDKs accept an optional parameter PreferredLocations that is an ordered list of Azure regions.

SDK 会自动将所有写入请求发送到当前写入区域。The SDK will automatically send all writes to the current write region. 所有读取请求将发送到首选位置列表中的第一个可用区域。All reads will be sent to the first available region in the preferred locations list. 如果请求失败,客户端会将请求转发到列表中的下一个区域。If the request fails, the client will fail down the list to the next region.

SDK 只会尝试读取首选位置中指定的区域。The SDK will only attempt to read from the regions specified in preferred locations. 因此,例如,如果 Azure Cosmos 帐户在四个区域中可用,但客户端只在 PreferredLocations 内指定了两个读取(非写入)区域,那么将不会从 PreferredLocations 中未指定的读取区域为读取提供服务。So, for example, if the Azure Cosmos account is available in four regions, but the client only specifies two read(non-write) regions within the PreferredLocations, then no reads will be served out of the read region that is not specified in PreferredLocations. 如果 PreferredLocations 列表中指定的读取区域不可用,将从写入区域为读取提供服务。If the read regions specified in the PreferredLocations list are not available, reads will be served out of write region.

应用程序可以通过检查 SDK 1.8 和更高版本中提供的两个属性(WriteEndpointReadEndpoint)来验证 SDK 选择的当前写入终结点和读取终结点。The application can verify the current write endpoint and read endpoint chosen by the SDK by checking two properties, WriteEndpoint and ReadEndpoint, available in SDK version 1.8 and above. 如果未设置 PreferredLocations 属性,则会从当前写入区域为所有请求提供服务。If the PreferredLocations property is not set, all requests will be served from the current write region.

如果未指定首选位置但使用了 setCurrentLocation 方法,则 SDK 会根据客户端运行的当前区域自动填充首选位置。If you don't specify the preferred locations but used the setCurrentLocation method, the SDK automatically populates the preferred locations based on the current region that the client is running in. SDK 会根据一个区域与当前区域的邻近程度对区域进行排序。The SDK orders the regions based on the proximity of a region to the current region.

.NET SDK.NET SDK

无需进行任何代码更改即可使用该 SDK。The SDK can be used without any code changes. 在此情况下,SDK 会自动将读取和写入请求定向到当前写入区域。In this case, the SDK automatically directs both reads and writes to the current write region.

在 .NET SDK 1.8 和更高版本中,DocumentClient 构造函数的 ConnectionPolicy 参数有一个名为 Microsoft.Azure.Documents.ConnectionPolicy.PreferredLocations 的属性。In version 1.8 and later of the .NET SDK, the ConnectionPolicy parameter for the DocumentClient constructor has a property called Microsoft.Azure.Documents.ConnectionPolicy.PreferredLocations. 此属性的类型为 Collection <string>,应包含区域名称的列表。This property is of type Collection <string> and should contain a list of region names. 字符串值已根据 Azure 区域页上的“区域名称”列设置格式,其第一个字符的前面和最后一个字符的后面均没有空格。The string values are formatted per the region name column on the Azure Regions page, with no spaces before or after the first and last character respectively.

当前写入终结点和读取终结点分别在 DocumentClient.WriteEndpoint 和 DocumentClient.ReadEndpoint 中提供。The current write and read endpoints are available in DocumentClient.WriteEndpoint and DocumentClient.ReadEndpoint respectively.

备注

不应将终结点 URL 视为长期不变的常量。The URLs for the endpoints should not be considered as long-lived constants. 服务随时会更新这些 URL。The service may update these at any point. SDK 会自动处理这种更改。The SDK handles this change automatically.

如果使用的是 .NET V2 SDK,请使用 PreferredLocations 属性设置首选区域。If you are using the .NET V2 SDK, use the PreferredLocations property to set the preferred region.

// Getting endpoints from application settings or other configuration location
Uri accountEndPoint = new Uri(Properties.Settings.Default.GlobalDatabaseUri);
string accountKey = Properties.Settings.Default.GlobalDatabaseKey;

ConnectionPolicy connectionPolicy = new ConnectionPolicy();

//Setting read region selection preference
connectionPolicy.PreferredLocations.Add(LocationNames.ChinaNorth); // first preference
connectionPolicy.PreferredLocations.Add(LocationNames.ChinaEast); // second preference
connectionPolicy.PreferredLocations.Add(LocationNames.ChinaEast2); // third preference

// initialize connection
DocumentClient docClient = new DocumentClient(
    accountEndPoint,
    accountKey,
    connectionPolicy);

// connect to DocDB
await docClient.OpenAsync().ConfigureAwait(false);

或者可使用 SetCurrentLocation 属性,让 SDK 根据邻近程度选择首选位置。Alternatively, you can use the SetCurrentLocation property and let the SDK choose the preferred location based on proximity.

// Getting endpoints from application settings or other configuration location
Uri accountEndPoint = new Uri(Properties.Settings.Default.GlobalDatabaseUri);
string accountKey = Properties.Settings.Default.GlobalDatabaseKey;

ConnectionPolicy connectionPolicy = new ConnectionPolicy();

connectionPolicy.SetCurrentLocation("China North 2"); /

// initialize connection
DocumentClient docClient = new DocumentClient(
    accountEndPoint,
    accountKey,
    connectionPolicy);

// connect to DocDB
await docClient.OpenAsync().ConfigureAwait(false);

Node.js/JavaScriptNode.js/JavaScript

备注

不应将终结点 URL 视为长期不变的常量。The URLs for the endpoints should not be considered as long-lived constants. 服务随时会更新这些 URL。The service may update these at any point. SDK 会自动处理这种更改。The SDK will handle this change automatically.

下面是 Node.js/Javascript 的代码示例。Below is a code example for Node.js/Javascript.

// Setting read region selection preference, in the following order -
// 1 - China North
// 2 - China East
// 3 - China East 2
const preferredLocations = ['China North', 'China East', 'China East 2'];

// initialize the connection
const client = new CosmosClient{ endpoint, key, connectionPolicy: { preferredLocations } });

Python SDKPython SDK

以下代码演示如何使用 Python SDK 设置首选位置:The following code shows how to set preferred locations by using the Python SDK:

connectionPolicy = documents.ConnectionPolicy()
connectionPolicy.PreferredLocations = ['China North', 'China East', 'China East 2']
client = cosmos_client.CosmosClient(ENDPOINT, {'masterKey': MASTER_KEY}, connectionPolicy)

Java V4 SDKJava V4 SDK

以下代码演示如何使用 Java SDK 设置首选位置:The following code shows how to set preferred locations by using the Java SDK:

Java SDK V4 (Maven com.azure::azure-cosmos) 异步 APIJava SDK V4 (Maven com.azure::azure-cosmos) Async API


ArrayList<String> preferredRegions = new ArrayList<String>();
preferredRegions.add("China North");
preferredRegions.add("China East");
preferredRegions.add("China East 2");

CosmosAsyncClient client =
        new CosmosClientBuilder()
                .endpoint(HOST)
                .key(MASTER_KEY)
                .preferredRegions(preferredRegions)
                .contentResponseOnWriteEnabled(true)
                .buildAsyncClient();

RESTREST

数据库帐户在多个区域中可用后,客户端可以通过对此 URI https://{databaseaccount}.documents.azure.cn/ 执行 GET 请求来查询该帐户的可用性Once a database account has been made available in multiple regions, clients can query its availability by performing a GET request on this URI https://{databaseaccount}.documents.azure.cn/

服务将返回副本的区域及其对应 Azure Cosmos DB 终结点 URI 的列表。The service will return a list of regions and their corresponding Azure Cosmos DB endpoint URIs for the replicas. 当前写入区域会在响应中指示。The current write region will be indicated in the response. 然后,客户端可为所有其他 REST API 请求选择适当的终结点,如下所示。The client can then select the appropriate endpoint for all further REST API requests as follows.

示例响应Example response

{
    "_dbs": "//dbs/",
    "media": "//media/",
    "writableLocations": [
        {
            "Name": "China North",
            "DatabaseAccountEndpoint": "https://globaldbexample-chinanorth.documents.azure.cn:443/"
        }
    ],
    "readableLocations": [
        {
            "Name": "China East",
            "DatabaseAccountEndpoint": "https://globaldbexample-chinaeast.documents.azure.cn:443/"
        }
    ],
    "MaxMediaStorageUsageInMB": 2048,
    "MediaStorageUsageInMB": 0,
    "ConsistencyPolicy": {
        "defaultConsistencyLevel": "Session",
        "maxStalenessPrefix": 100,
        "maxIntervalInSeconds": 5
    },
    "addresses": "//addresses/",
    "id": "globaldbexample",
    "_rid": "globaldbexample.documents.azure.cn",
    "_self": "",
    "_ts": 0,
    "_etag": null
}
  • 所有 PUT、POST 和 DELETE 请求必须转到指示的写入 URIAll PUT, POST and DELETE requests must go to the indicated write URI
  • 所有 GET 和其他只读请求(例如查询)可以转到客户端选择的任何终结点All GETs and other read-only requests (for example queries) may go to any endpoint of the client's choice

向只读区域发出的写入请求会失败并出现 HTTP 错误代码 403(“禁止”)。Write requests to read-only regions will fail with HTTP error code 403 ("Forbidden").

如果在客户端初始发现阶段过后写入区域发生更改,则向先前写入区域进行的后续写入会失败并出现 HTTP 错误代码 403(“禁止”)。If the write region changes after the client's initial discovery phase, subsequent writes to the previous write region will fail with HTTP error code 403 ("Forbidden"). 然后,客户端应再次对区域列表执行 GET 以获取更新的写入区域。The client should then GET the list of regions again to get the updated write region.

本教程到此结束。That's it, that completes this tutorial. 阅读 Azure Cosmos DB 中的一致性级别,了解如何管理多区域复制帐户的一致性。You can learn how to manage the consistency of your multiple-regionally replicated account by reading Consistency levels in Azure Cosmos DB. 有关 Azure Cosmos DB 中多区域数据库复制工作原理的详细信息,请参阅使用 Cosmos DB 多区域分配数据And for more information about how multiple-region database replication works in Azure Cosmos DB, see Distribute data multiple-regionally with Azure Cosmos DB.

后续步骤Next steps

在本教程中,已完成以下内容:In this tutorial, you've done the following:

  • 使用 Azure 门户配置多区域分发Configure multiple-region distribution using the Azure portal
  • 使用 SQL API 配置多区域分发Configure multiple-region distribution using the SQL APIs

现在可以继续学习下一个教程,了解如何使用 Azure Cosmos DB 本地模拟器在本地开发。You can now proceed to the next tutorial to learn how to develop locally using the Azure Cosmos DB local emulator.