管理 Azure Cosmos DB 中的一致性層級

適用於:NoSQL

本文說明如何管理 Azure Cosmos DB 中的一致性層級。 您會了解如何設定預設一致性、覆寫預設一致性、手動管理工作階段權杖,並了解概率限定過期 (PBS) 計量。

變更帳戶層級一致性時,請務必重新部署應用程式,以及進行必要的程式碼修改並套用變更。

注意

建議您使用 Azure Az PowerShell 模組來與 Azure 互動。 請參閱安裝 Azure PowerShell 以開始使用。 若要了解如何移轉至 Az PowerShell 模組,請參閱將 Azure PowerShell 從 AzureRM 移轉至 Az

設定預設一致性層級

預設一致性層級是用戶端依預設使用的一致性層級。

若要檢視或修改預設一致性層級,請登入 Azure 入口網站。 尋找您的 Azure Cosmos DB 帳戶,然後開啟 [預設一致性] 窗格。 選取要作為新預設值的一致性層級,然後選取 [儲存]。 Azure 入口網站也會提供不同一致性層級 (含音符) 的視覺效果。

Azure 入口網站 中的一致性功能表

覆寫預設一致性層級

用戶端可以覆寫服務所設定的預設一致性層級。 一致性層級可以根據每個要求來設定,這會覆寫在帳戶層級設定的預設一致性層級。

提示

一致性只能在 SDK 執行個體或要求層級放寬。 若要從較弱的一致性移動到較強的一致性,請更新 Azure Cosmos DB 帳戶的預設一致性。

提示

覆寫預設一致性層級僅適用於 SDK 用戶端內的讀取。 根據預設,針對強式一致性設定的帳戶仍會以同步方式將資料寫入和複寫至帳戶中的每個區域。 當 SDK 用戶端執行個體或要求以工作階段或較弱的一致性對此進行覆寫時,則會使用單一複本來執行讀取。 請參閱一致性層級和輸送量以取得詳細資料。

.NET SDK

// 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.ReadDocumentAsync(collectionUri, document, requestOptions);

Java V4 SDK

Java SDK V4 (Maven com.azure::azure-cosmos) 非同步 API


CosmosAsyncClient client =
        new CosmosClientBuilder()
                .endpoint(HOST)
                .key(MASTER_KEY)
                .consistencyLevel(ConsistencyLevel.EVENTUAL)
                .buildAsyncClient();

Java V2 SDK

非同步 Java V2 SDK (Maven com.microsoft.azure::azure-cosmosdb)

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

Node.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 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)

使用工作階段權杖

Azure Cosmos DB 中的其中一個一致性層級是「工作階段」一致性。 這是預設套用至 Azure Cosmos DB 帳戶的預設層級。 使用工作階段一致性時,會指派新的 SessionToken 給針對 Azure Cosmos DB 的每個新寫入要求。 CosmosClient 會在內部針對每個讀取/查詢要求使用此權杖,以確保維持設定的一致性層級。

在某些情況下,您必須自行管理此會話。 假設有一個具有多個節點的 Web 應用程式,每個節點都有自己的 CosmosClient 執行個體。 如果您想要讓這些節點參與相同的會話(能夠一致地跨 Web 層讀取您自己的寫入),您必須使用 Cookie 或其他一些機制,從寫入動作的 FeedResponse<T> 將 SessionToken 傳送給終端使用者,並讓該令牌流回 Web 層,最後是 CosmosClient 進行後續讀取。 如果您使用迴圈配置資源負載平衡器來維護要求之間的會話親和性,例如 Azure Load Balancer,讀取可能會落在建立會話的寫入要求的不同節點上。

如果您未如上所述將 Azure Cosmos DB SessionToken 流過,最後可能會有一段時間不一致的讀取結果。

Azure Cosmos DB 中的工作階段權杖會繫結至分割區,也就是只會與一個分割區相關聯。 為了確保可以讀取您的寫入,請使用上次為相關項目產生的工作階段權杖。 若要手動管理工作階段權杖,請從回應中取得工作階段權杖,並就個別要求加以設定。 如果不需要手動管理工作階段權杖,則不需要使用下列範例。 SDK 會自動持續追蹤工作階段權杖。 如果未手動設定工作階段權杖,則 SDK 預設會使用最新的工作階段權杖。

.NET SDK

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

Java V4 SDK

Java SDK V4 (Maven com.azure::azure-cosmos) 非同步 API


// Get session token from response
CosmosItemResponse<JsonNode> response = container.readItem(itemId, new PartitionKey(partitionKey), JsonNode.class).block();
String sessionToken = response.getSessionToken();

// Resume the session by setting the session token on the RequestOptions
CosmosItemRequestOptions options = new CosmosItemRequestOptions();
options.setSessionToken(sessionToken);
CosmosItemResponse<JsonNode> response2 = container.readItem(itemId, new PartitionKey(partitionKey), JsonNode.class).block();

Java V2 SDK

非同步 Java V2 SDK (Maven com.microsoft.azure::azure-cosmosdb)

// 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);

Node.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 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) 計量

最終一致性的界定標準為何? 針對平均案例,我們可以針對版本歷程記錄和時間提供過時界限。 機率限定過期 (PBS) 計量會嘗試量化過期的機率,並將其顯示為計量。

若要檢視 PBS 計量,請在 Azure 入口網站中移至您的 Azure Cosmos DB 帳戶。 接著,開啟 [計量 (傳統)] 窗格,然後選取 [一致性] 索引標籤。查看名為「依據您的工作負載,強式一致讀取的可能性 (請參閱 PBS)」的圖形。

Azure 入口網站 中的 PBS 圖表

下一步

深入了解如何管理資料衝突,或繼續 Azure Cosmos DB 中的下一個重要概念。 請參閱以下文章: