在 Azure Cosmos DB 中管理一致性级别Manage consistency levels in Azure Cosmos DB

本文介绍了如何在 Azure Cosmos DB 中管理一致性级别。This article explains how to manage consistency levels in Azure Cosmos DB. 你将了解如何配置默认一致性级别、替代默认一致性、手动管理会话令牌以及了解概率有限过期 (PBS) 指标。You learn how to configure the default consistency level, override the default consistency, manually manage session tokens, and understand the Probabilistically Bounded Staleness (PBS) metric.

Note

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

配置默认一致性级别Configure the default consistency level

默认一致性级别是客户端默认情况下使用的一致性级别。The default consistency level is the consistency level that clients use by default. 客户端总是可以替代它。Clients can always override it.

CLICLI

# create with a default consistency
az cosmosdb create --name <name of Cosmos DB Account> --resource-group <resource group name> --default-consistency-level Session

# update an existing account's default consistency
az cosmosdb update --name <name of Cosmos DB Account> --resource-group <resource group name> --default-consistency-level Eventual

PowerShellPowerShell

此示例在“中国东部”和“中国北部”区域中创建启用了多个写入区域的新 Azure Cosmos 帐户。This example creates a new Azure Cosmos account with multiple write regions enabled, in China East and China North regions. 默认一致性级别设置为“会话”一致性 。The default consistency level is set to Session consistency.

$locations = @(@{"locationName"="China East"; "failoverPriority"=0},
             @{"locationName"="China North"; "failoverPriority"=1})

$iprangefilter = ""

$consistencyPolicy = @{"defaultConsistencyLevel"="Session"}

$CosmosDBProperties = @{"databaseAccountOfferType"="Standard";
                        "locations"=$locations;
                        "consistencyPolicy"=$consistencyPolicy;
                        "ipRangeFilter"=$iprangefilter;
                        "enableMultipleWriteLocations"="true"}

New-AzResource -ResourceType "Microsoft.DocumentDb/databaseAccounts" `
  -ApiVersion "2015-04-08" `
  -ResourceGroupName "myResourceGroup" `
  -Location "China East" `
  -Name "myCosmosDbAccount" `
  -Properties $CosmosDBProperties

Azure 门户Azure portal

若要查看或修改默认一致性级别,请登录到 Azure 门户。To view or modify the default consistency level, sign in to the Azure portal. 找到你的 Azure Cosmos 帐户,打开“默认一致性”窗格 。Find your Azure Cosmos account, and open the Default consistency pane. 选择你希望用作新的默认值的一致性级别,然后选择“保存” 。Select the level of consistency you want as the new default, and then select Save.

Azure 门户中的一致性菜单

替代默认一致性级别Override the default consistency level

客户端可以重写由服务设置的默认一致性级别。Clients can override the default consistency level that is set by the service. 可以在每个请求上设置一致性级别,这将替代在帐户级别设置的默认一致性级别。Consistency level can be set on a per request, which overrides the default consistency level set at the account level.

.NET SDK V2.NET SDK V2

// Override consistency at the client level
documentClient = new DocumentClient(new Uri(endpoint), authKey, connectionPolicy, ConsistencyLevel.Eventual);

// Override consistency at the request level via request options
RequestOptions requestOptions = new RequestOptions { ConsistencyLevel = ConsistencyLevel.Eventual };

var response = await client.CreateDocumentAsync(collectionUri, document, requestOptions);

.NET SDK V3.NET SDK V3

// Override consistency at the request level via request options
ItemRequestOptions requestOptions = new ItemRequestOptions { ConsistencyLevel = ConsistencyLevel.Strong };

var response = await client.GetContainer(databaseName, containerName)
    .CreateItemAsync(
        item, 
        new PartitionKey(itemPartitionKey), 
        requestOptions);

Java 异步 SDKJava Async SDK

// Override consistency at the client level
ConnectionPolicy policy = new ConnectionPolicy();

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

Java 同步 SDKJava Sync SDK

// Override consistency at the client level
ConnectionPolicy connectionPolicy = new ConnectionPolicy();
DocumentClient client = new DocumentClient(accountEndpoint, accountKey, connectionPolicy, ConsistencyLevel.Eventual);

Node.js/JavaScript/TypeScript SDKNode.js/JavaScript/TypeScript SDK

// Override consistency at the client level
const client = new CosmosClient({
  /* other config... */
  consistencyLevel: ConsistencyLevel.Eventual
});

// Override consistency at the request level via request options
const { body } = await item.read({ consistencyLevel: ConsistencyLevel.Eventual });

Python SDKPython SDK

# Override consistency at the client level
connection_policy = documents.ConnectionPolicy()
client = cosmos_client.CosmosClient(self.account_endpoint, {
                                    'masterKey': self.account_key}, connection_policy, documents.ConsistencyLevel.Eventual)

利用会话令牌Utilize session tokens

Azure Cosmos DB 中的一致性级别之一是“会话”一致性 。One of the consistency levels in Azure Cosmos DB is Session consistency. 这是默认情况下应用于 Cosmos 帐户的默认级别。This is the default level applied to Cosmos accounts by default. 使用“会话”一致性时,客户端将在内部的每个读取/查询请求中使用会话令牌,以确保维持设置的一致性级别 。When working with Session consistency, the client will use a session token internally with each read/query request to ensure that the set consistency level is maintained.

若要手动管理会话令牌,请从响应中获取会话令牌并针对每个请求设置它们。To manage session tokens manually, get the session token from the response and set them per request. 如果不需手动管理会话令牌,则不需要使用这些示例。If you don't need to manage session tokens manually, you don't need to use these samples. SDK 会自动跟踪会话令牌。The SDK keeps track of session tokens automatically. 如果未手动设置会话令牌,则默认情况下,SDK 使用最新的会话令牌。If you don't set the session token manually, by default, the SDK uses the most recent session token.

.NET SDK V2.NET SDK V2

var response = await client.ReadDocumentAsync(
                UriFactory.CreateDocumentUri(databaseName, collectionName, "SalesOrder1"));
string sessionToken = response.SessionToken;

RequestOptions options = new RequestOptions();
options.SessionToken = sessionToken;
var response = await client.ReadDocumentAsync(
                UriFactory.CreateDocumentUri(databaseName, collectionName, "SalesOrder1"), options);

.NET SDK V3.NET SDK V3

Container container = client.GetContainer(databaseName, collectionName);
ItemResponse<SalesOrder> response = await container.CreateItemAsync<SalesOrder>(salesOrder);
string sessionToken = response.Headers.Session;

ItemRequestOptions options = new ItemRequestOptions();
options.SessionToken = sessionToken;
ItemResponse<SalesOrder> response = await container.ReadItemAsync<SalesOrder>(salesOrder.Id, new PartitionKey(salesOrder.PartitionKey), options);

Java 异步 SDKJava Async SDK

// Get session token from response
RequestOptions options = new RequestOptions();
options.setPartitionKey(new PartitionKey(document.get("mypk")));
Observable<ResourceResponse<Document>> readObservable = client.readDocument(document.getSelfLink(), options);
readObservable.single()           // we know there will be one response
  .subscribe(
      documentResourceResponse -> {
          System.out.println(documentResourceResponse.getSessionToken());
      },
      error -> {
          System.err.println("an error happened: " + error.getMessage());
      });

// Resume the session by setting the session token on RequestOptions
RequestOptions options = new RequestOptions();
requestOptions.setSessionToken(sessionToken);
Observable<ResourceResponse<Document>> readObservable = client.readDocument(document.getSelfLink(), options);

Java 同步 SDKJava Sync SDK

// Get session token from response
ResourceResponse<Document> response = client.readDocument(documentLink, null);
String sessionToken = response.getSessionToken();

// Resume the session by setting the session token on the RequestOptions
RequestOptions options = new RequestOptions();
options.setSessionToken(sessionToken);
ResourceResponse<Document> response = client.readDocument(documentLink, options);

Node.js/JavaScript/TypeScript SDKNode.js/JavaScript/TypeScript SDK

// Get session token from response
const { headers, item } = await container.items.create({ id: "meaningful-id" });
const sessionToken = headers["x-ms-session-token"];

// Immediately or later, you can use that sessionToken from the header to resume that session.
const { body } = await item.read({ sessionToken });

Python SDKPython SDK

// Get the session token from the last response headers
item = client.ReadItem(item_link)
session_token = client.last_response_headers["x-ms-session-token"]

// Resume the session by setting the session token on the options for the request
options = {
    "sessionToken": session_token
}
item = client.ReadItem(doc_link, options)

监视概率有限过期 (PBS) 指标Monitor Probabilistically Bounded Staleness (PBS) metric

最终一致性的最终程度如何?How eventual is eventual consistency? 对于普通情况,我们是否可以提供版本历史和时间方面的过期限度。For the average case, can we offer staleness bounds with respect to version history and time. 概率有限过期 (PBS) 指标尝试量化过期的概率并将其显示为指标。The Probabilistically Bounded Staleness (PBS) metric tries to quantify the probability of staleness and shows it as a metric. 若要查看 PBS 指标,请在 Azure 门户中转到你的 Cosmos 帐户。To view the PBS metric, go to your Azure Cosmos account in the Azure portal. 打开“指标” 窗格,然后选择“一致性” 选项卡。查看名为“基于工作负载的强一致性读取的概率(请参阅 PBS)”的图。 Open the Metrics pane, and select the Consistency tab. Look at the graph named Probability of strongly consistent reads based on your workload (see PBS).

Azure 门户中的 PBS 图

后续步骤Next steps

详细了解如何管理数据冲突,或者继续了解 Azure Cosmos DB 中的下一个关键概念。Learn more about how to manage data conflicts, or move on to the next key concept in Azure Cosmos DB. 请参阅以下文章:See the following articles: