在使用 Azure Cosmos DB 的应用程序配置多区域写入Configure multi-region writes in your applications that use Azure Cosmos DB

适用于: SQL API

创建启用了多个写入区域的帐户后,必须在应用程序中对 DocumentClient 的 ConnectionPolicy 进行两处更改,以启用 Azure Cosmos DB 中的多区域写入和多宿主功能。Once an account has been created with multiple write regions enabled, you must make two changes in your application to the ConnectionPolicy for the DocumentClient to enable the multi-region writes and multi-homing capabilities in Azure Cosmos DB. 在 ConnectionPolicy 中,将 UseMultipleWriteLocations 设置为 true,并将部署应用程序的区域的名称传递给 SetCurrentLocation。Within the ConnectionPolicy, set UseMultipleWriteLocations to true and pass the name of the region where the application is deployed to SetCurrentLocation. 这将根据传入位置的地理接近性填充 PreferredLocations 属性。This will populate the PreferredLocations property based on the geo-proximity from location passed in. 如果稍后将新区域添加到帐户中,则无需更新或重新部署应用程序,它将自动检测距离较近的区域,并在发生区域事件时自动定位到该区域。If a new region is later added to the account, the application does not have to be updated or redeployed, it will automatically detect the closer region and will auto-home on to it should a regional event occur.

备注

最初配置有单个写入区域的 Cosmos 帐户可以配置为多个写入区域且停机时间为零。Cosmos accounts initially configured with single write region can be configured to multiple write regions with zero down time. 若要了解详细信息,请参阅配置多个写入区域To learn more see, Configure multiple-write regions

Azure 门户Azure portal

若要从 Azure 门户启用多区域写入,请执行以下步骤:To enable multi-region writes from Azure portal, use the following steps:

  1. 登录到 Azure 门户Sign-in to the Azure portal.

  2. 导航到 Azure Cosmos 帐户,然后从菜单中打开“多区域复制数据”窗格。Navigate to your Azure Cosmos account and from the menu, open the Replicate data multiple-regionally pane.

  3. 在“多区域写入”选项下,选择“启用”。Under the Multi-region writes option, choose enable. 它会自动将现有区域添加到读取和写入区域。It automatically adds the existing regions to read and write regions.

  4. 可以通过选择地图上的图标或选择“添加区域”按钮来添加其他区域。You can add additional regions by selecting the icons on the map or by selecting the Add region button. 你添加的所有区域都会启用读取和写入功能。All the regions you add will have both read and writes enabled.

  5. 更新区域列表后,请选择“保存”以应用所做的更改。After you update the region list, select save to apply the changes.

    使用 Azure 门户启用多区域写入的屏幕截图

.NET SDK v2.NET SDK v2

若要在应用程序中启用多区域写入,请将 UseMultipleWriteLocations 设置为 trueTo enable multi-region writes in your application, set UseMultipleWriteLocations to true. 此外,将 SetCurrentLocation 设置为在其中部署应用程序并复制 Azure Cosmos DB 的区域:Also, set SetCurrentLocation to the region in which the application is being deployed and where Azure Cosmos DB is replicated:

ConnectionPolicy policy = new ConnectionPolicy
    {
        ConnectionMode = ConnectionMode.Direct,
        ConnectionProtocol = Protocol.Tcp,
        UseMultipleWriteLocations = true
    };
policy.SetCurrentLocation("China North 2");

.NET SDK v3.NET SDK v3

若要在应用程序中启用多区域写入,请将 ApplicationRegion 设置为在其中部署应用程序并复制 Cosmos DB 的区域:To enable multi-region writes in your application, set ApplicationRegion to the region in which the application is being deployed and where Cosmos DB is replicated:

CosmosClient cosmosClient = new CosmosClient(
    "<connection-string-from-portal>", 
    new CosmosClientOptions()
    {
        ApplicationRegion = Regions.ChinaNorth2,
    });

(可选)可以使用 CosmosClientBuilderWithApplicationRegion 来获得相同的结果:Optionally, you can use the CosmosClientBuilder and WithApplicationRegion to achieve the same result:

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder("<connection-string-from-portal>")
            .WithApplicationRegion(Regions.ChinaNorth2);
CosmosClient client = cosmosClientBuilder.Build();

Java V4 SDKJava V4 SDK

若要在应用程序中启用多区域写入,请在客户端生成器中调用 .multipleWriteRegionsEnabled(true).preferredRegions(preferredRegions),其中 preferredRegions 是包含一个元素的 List,即正在部署应用程序和复制 Cosmos DB 的区域:To enable multi-region writes in your application, call .multipleWriteRegionsEnabled(true) and .preferredRegions(preferredRegions) in the client builder, where preferredRegions is a List containing one element - that is the region in which the application is being deployed and where Cosmos DB is replicated:

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(region);

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

Async Java V2 SDKAsync Java V2 SDK

Java V2 SDK 使用 Maven com.microsoft.azure::azure-cosmosdbThe Java V2 SDK used the Maven com.microsoft.azure::azure-cosmosdb. 若要在应用程序中启用多区域写入,请设置 policy.setUsingMultipleWriteLocations(true),并将 policy.setPreferredLocations 设置为在其中部署应用程序并复制 Cosmos DB 的区域:To enable multi-region writes in your application, set policy.setUsingMultipleWriteLocations(true) and set policy.setPreferredLocations to the region in which the application is being deployed and where Cosmos DB is replicated:

ConnectionPolicy policy = new ConnectionPolicy();
policy.setUsingMultipleWriteLocations(true);
policy.setPreferredLocations(Collections.singletonList(region));

AsyncDocumentClient client =
    new AsyncDocumentClient.Builder()
        .withMasterKeyOrResourceToken(this.accountKey)
        .withServiceEndpoint(this.accountEndpoint)
        .withConsistencyLevel(ConsistencyLevel.Eventual)
        .withConnectionPolicy(policy).build();

Node.js、JavaScript 和 TypeScript SDKNode.js, JavaScript, and TypeScript SDKs

若要在应用程序中启用多区域写入,请将 connectionPolicy.UseMultipleWriteLocations 设置为 trueTo enable multi-region writes in your application, set connectionPolicy.UseMultipleWriteLocations to true. 此外,将 connectionPolicy.PreferredLocations 设置为在其中部署应用程序并复制 Cosmos DB 的区域:Also, set connectionPolicy.PreferredLocations to the region in which the application is being deployed and where Cosmos DB is replicated:

const connectionPolicy: ConnectionPolicy = new ConnectionPolicy();
connectionPolicy.UseMultipleWriteLocations = true;
connectionPolicy.PreferredLocations = [region];

const client = new CosmosClient({
  endpoint: config.endpoint,
  auth: { masterKey: config.key },
  connectionPolicy,
  consistencyLevel: ConsistencyLevel.Eventual
});

Python SDKPython SDK

若要在应用程序中启用多区域写入,请将 connection_policy.UseMultipleWriteLocations 设置为 trueTo enable multi-region writes in your application, set connection_policy.UseMultipleWriteLocations to true. 此外,将 connection_policy.PreferredLocations 设置为在其中部署应用程序并复制 Cosmos DB 的区域。Also, set connection_policy.PreferredLocations to the region in which the application is being deployed and where Cosmos DB is replicated.

connection_policy = documents.ConnectionPolicy()
connection_policy.UseMultipleWriteLocations = True
connection_policy.PreferredLocations = [region]

client = cosmos_client.CosmosClient(self.account_endpoint, {
                                    'masterKey': self.account_key}, connection_policy, documents.ConsistencyLevel.Session)

后续步骤Next steps

请阅读以下文章:Read the following articles: