次の方法で共有


Azure Cosmos DB で一貫性レベルを管理する

適用対象: NoSQL

この記事では、Azure Cosmos DB で一貫性レベルを管理する方法について説明します。 読者は、既定の一貫性レベルを構成する方法、既定の一貫性をオーバーライドする方法、セッション トークンを手動を管理する方法、および確率論的有界整合性制約 (PBS) メトリックを確認する方法について学習します。

アカウント レベルの整合性を変更するときは、アプリケーションを再デプロイし、これらの変更を適用するために必要なコード変更を行ってください。

Azure を操作するには、Azure Az PowerShell モジュールを使用することをお勧めします。 作業を始めるには、「Azure PowerShell をインストールする」を参照してください。 Az PowerShell モジュールに移行する方法については、「AzureRM から Az への Azure PowerShell の移行」を参照してください。

既定の整合性レベルを構成する

既定の整合性レベルの詳細については、 Azure Cosmos DB の整合性レベルに関するページを参照してください。

既定の整合性レベルを表示または変更するには:

  1. Azure portal にサインインします。

  2. Azure Cosmos DB アカウントを見つけて、[既定の整合性] ウィンドウを開きます。

  3. 目的の一貫性レベルを新しい既定として選択し、 [保存] を選択します。

Azure portal では、音符によるさまざまな一貫性レベルの視覚化も提供しています。

Azure portal の [整合性] メニューのスクリーンショット。

既定の一貫性レベルを上書きする

サービスは既定の整合性レベルを設定しますが、クライアントはそれをオーバーライドできます。 整合性レベルは要求ごとに設定できます。これにより、アカウント レベルで設定される既定の整合性レベルがオーバーライドされます。

ヒント

整合性は、SDK インスタンスまたは要求レベルでのみ緩和されます。 弱い整合性からより強い整合性に移行するには、Azure Cosmos DB アカウントのデフォルトの整合性を更新します。

ヒント

既定の整合性レベルのオーバーライドは、SDK クライアント内の読み取りにのみ適用されます。 既定で強力な整合性を確保するように構成されたアカウントは、アカウント内のすべてのリージョンにデータを同期的に書き込んでレプリケートします。 SDK クライアント インスタンスまたは要求がこのレベルをセッションまたは弱い整合性でオーバーライドすると、読み取りは 1 つのレプリカを使用して実行されます。 詳しくは、「整合性レベルとスループット」をご覧ください。

.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

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

Go SDK (ソフトウェア開発キット)

要求で整合性レベルを定義します。

container, _ := c.NewContainer("moviesdb", "movies")

container.NewQueryItemsPager("select * from c", azcosmos.NewPartitionKey(), &azcosmos.QueryOptions{
		ConsistencyLevel: azcosmos.ConsistencyLevelEventual.ToPtr(),
})

container.ReadItem(context.Background(), azcosmos.NewPartitionKeyString("Quentin Tarantino"), "Pulp Fiction", &azcosmos.ItemOptions{
		ConsistencyLevel: azcosmos.ConsistencyLevelStrong.ToPtr(),
})

セッション トークンを利用する

Azure Cosmos DB の整合性レベルの 1 つは 、セッション の整合性です。 このレベルは、Azure Cosmos DB アカウントに適用される既定のレベルです。 セッションの整合性を使用する場合、Azure Cosmos DB に対するすべての新しい書き込み要求に新しい SessionToken が割り当てられます。 CosmosClient は、このトークンを読み取り/クエリ要求ごとに内部的に使用して、設定された整合性レベルが維持されるようにします。

シナリオによっては、このセッションを自分で管理する必要があります。 複数のノードを持つ Web アプリケーションについて考えてみましょう。各ノードには CosmosClient の独自のインスタンスがあります。 これらのノードを同じセッションに参加させる (Web 層間で独自の書き込みを一貫して読み取ることができるようにする) 場合は、Cookie またはその他のメカニズムを使用して、書き込みアクションの SessionToken を FeedResponse<T> からエンド ユーザーに送信し、そのトークンを Web 層に戻し、最終的に CosmosClient に送信して以降の読み取りを行う必要があります。 Azure Load Balancer などの要求間のセッション アフィニティを維持しないラウンド ロビン ロード バランサーを使用している場合、読み取りは、セッションが作成された書き込み要求とは別のノードに配置される可能性があります。

Azure Cosmos DB SessionToken をフローしない場合は、しばらくの間、読み取り結果の整合性が失われます。

Azure Cosmos DB のセッション トークンはパーティション バインドです。つまり、1 つのパーティションにのみ関連付けられます。 書き込みを読み取れるようにするには、関連する項目に対して最後に生成されたセッション トークンを使用します。 セッション トークンを手動で管理するには、応答からセッション トークンを取得し、それらを要求ごとに設定します。 セッション トークンを手動で管理する必要がない場合は、これらのサンプルを使用する必要はありません。 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

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

Go SDK (ソフトウェア開発キット)

// Get the session token from the create item response
resp, _ := container.CreateItem(context.Background(), azcosmos.NewPartitionKeyString("Quentin Tarantino"), movie, &azcosmos.ItemOptions{
	ConsistencyLevel: azcosmos.ConsistencyLevelSession.ToPtr(),
})

// Use the session token to read the item
container.ReadItem(context.Background(), azcosmos.NewPartitionKeyString("Quentin Tarantino"), movieId, &azcosmos.ItemOptions{
	SessionToken: resp.SessionToken,
})

確率的に有界整合性制約メトリックを監視する

最終的な整合性は、どの程度のものなのでしょうか。 平均的なケースでは、バージョン履歴と時刻に関して、古さの限度を提示できます。 確率論的有界整合性制約 (PBS) メトリックは、制約の確率を定量化し、メトリックとして表示しようとします。

PBS メトリックを表示するには:

  1. Azure portal で Azure Cosmos DB アカウントに移動します。

  2. [メトリック (クラシック)] ウィンドウを開き、[整合性] タブを選択します。

  3. ワークロードに基づいて、厳密に一貫性のある読み取りの確率という名前のグラフを確認します (PBS を参照)。

Azure portal の確率的有界整合性制約グラフのスクリーンショット。

次のステップ

データの競合を管理する方法について学習するか、Azure Cosmos DB に関する次の主要概念に進んでください。