自己投資としてチャレンジしている内容を Blog で公開しています。今回は前回同様 Azure Cosmos DB (SQL API) への接続方法について深堀します。
————————————
▼1. Azure Cosmos DB への 接続の仕方
————————————-
Cosmos DB の接続の方法に以下の 2 種類のモードがあります。
違いは接続のプロトコルとクライアントサイドのパフォーマンスにあります。
1-1. Direct Mode
TCP プロトコルを利用した接続。最初の認証に TLS を利用しトラフィックは暗号化されている。Gateway Mode に比べネットワークのホップ数(中継回数)が少なく、クライアントサイドのパフォーマンスが Gateway Mode に比べてよい。
1-2. Gateway Mode
HTTPS のプロトコルを利用したセキュアな接続。Direct Mode に比べネットワークのホップ数 (中継回数) が多く、Cosmos DB への接続に時間がかかり、クライアントサイドのパフォーマンスに影響を与える。
————————————
▼2. 事前準備
————————————
事前準備は “【プログラミング学習】Java Azure Cosmos DB (SQL API) への接続方法 No.11 ” と同じです。
2-1. 以下のサイトから無料で利用できる Azure Cosmos DB を用意します。Azure を利用するために必要な Subscription を用意する必要もありません。
https://azure.microsoft.com/ja-jp/try/cosmosdb/
2-2. Maven auto-import を IntelliJ IDEA で有効にする。
IntelliJ のメニューにある View -> Tool Windows -> Maven を選択すると以下のように Maven が右上に表示されます。

さらに下のように Toggle Auto Reload Mode をクリックし、Enable auto-reload after any changes を選択します。

2-3. Pom.xml に以下のように必要なライブラリーを指定します。その後、上記 2-2 設定により、ライブラリーが自動でダウンロードされます。File -> Project Structure -> Project Settings -> Libraries で自動でダウンロードされたライブラリーが確認できます。
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.azure/azure-cosmos -->
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-tcnative</artifactId>
<version>2.0.31.Final</version>
<classifier>linux-x86_64</classifier>
</dependency>
</dependencies>
————————————
▼3. Cosmos DB への接続
————————————
Direct Mode と Gateway Mode それぞれのコードを紹介します。
3-1. Direct Modeの場合
3-1-1. 以下のコードで Azure Cosmos DB に接続します。
end_point の xxx と、master_key の xxx は、それぞれ利用する Cosmos DB のアカウント名とキーに書き換えます。
Direct Mode を利用するために directMode(DirectConnectionConfig.getDefaultConfig()) を指定しています。
import com.azure.cosmos.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
public class conCosmosDBv3 {
protected static final Logger log = LoggerFactory.getLogger(conCosmosDBv3.class);
public static void main(String[] args) {
String databaseName = "testcosmosdb";
String end_point = "https://xxxx.documents.azure.com:443";
String master_key = "xxxx";
try (CosmosClient cosmosClient = new CosmosClientBuilder().endpoint(end_point).key(master_key).directMode(DirectConnectionConfig.getDefaultConfig()).consistencyLevel(ConsistencyLevel.SESSION).connectionSharingAcrossClientsEnabled(true).contentResponseOnWriteEnabled(true).userAgentSuffix("My-Application-clienttest").preferredRegions(Collections.singletonList("West US")).buildClient()){
log.info("The connection to Cosmos DB succeeded.");
}catch(CosmosException e){
e.printStackTrace();
}
}
}
3-1-2. 実行結果は以下となります。
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Initializing DocumentClient with serviceEndpoint [https://xxx.documents.azure.com:443], connectionPolicy [ConnectionPolicy{requestTimeout=PT5S, connectionMode=DIRECT, maxConnectionPoolSize=1000, idleConnectionTimeout=PT0S, userAgentSuffix='My-Application-clienttest', throttlingRetryOptions=RetryOptions{maxRetryAttemptsOnThrottledRequests=9, maxRetryWaitTime=PT30S}, endpointDiscoveryEnabled=true, preferredRegions=[West US], multipleWriteRegionsEnabled=true, proxyType=null, inetSocketProxyAddress=null, readRequestsFallbackEnabled=true, connectTimeout=PT1M, idleEndpointTimeout=PT1M10S, maxConnectionsPerEndpoint=130, maxRequestsPerConnection=30}], consistencyLevel [Session], directModeProtocol [Tcp] [main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - creating a new shared HttpClient [parallel-1] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Getting database account endpoint from https://xxx.documents.azure.com:443 [main] INFO com.azure.cosmos.implementation.directconnectivity.SharedTransportClient - creating a new shared RntbdTransportClient [main] INFO conCosmosDBv3 - The connection to Cosmos DB succeeded. [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down ... [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Closing Global Endpoint Manager ... [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Closing StoreClientFactory ... [main] INFO com.azure.cosmos.implementation.directconnectivity.SharedTransportClient - closing one reference to the shared RntbdTransportClient, the number of remaining references is 0 [main] INFO com.azure.cosmos.implementation.directconnectivity.SharedTransportClient - All references to shared RntbdTransportClient are closed. Closing the underlying RntbdTransportClient [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down reactorHttpClient ... [main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - closing one reference to the shared HttpClient, the number of remaining references is 0 [main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - All references to shared HttpClient are closed. Closing the underlying HttpClient [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down completed.
3-2. Gateway Modeの場合
end_point の xxx と、master_key の xxx は、それぞれ利用する Cosmos DB のアカウント名とキーに書き換えます。
Gateway Mode を利用するために gatewayMode(GatewayConnectionConfig.getDefaultConfig()) を指定しています。
import com.azure.cosmos.*;
import com.azure.cosmos.models.CosmosDatabaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
public class conCosmosDBv4 {
protected static final Logger log = LoggerFactory.getLogger(conCosmosDBv4.class);
public static void main(String[] args) {
String databaseName = "testcosmosdb";
String end_point = "https://xxxx.documents.azure.com:443";
String master_key = "xxxxx";
try (CosmosClient cosmosClient = new CosmosClientBuilder().endpoint(end_point).key(master_key).gatewayMode(GatewayConnectionConfig.getDefaultConfig()).consistencyLevel(ConsistencyLevel.SESSION).connectionSharingAcrossClientsEnabled(true).contentResponseOnWriteEnabled(true).userAgentSuffix("My-Application-clienttest").preferredRegions(Collections.singletonList("West US")).buildClient()){
log.info("The connection to Cosmos DB succeeded using GatewayMode.");
}catch(CosmosException e){
e.printStackTrace();
}
}
}
3-2-2. 実行結果は以下となります。
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Initializing DocumentClient with serviceEndpoint [https://xxx.documents.azure.com:443], connectionPolicy [ConnectionPolicy{requestTimeout=PT5S, connectionMode=GATEWAY, maxConnectionPoolSize=1000, idleConnectionTimeout=PT1M, userAgentSuffix='My-Application-clienttest', throttlingRetryOptions=RetryOptions{maxRetryAttemptsOnThrottledRequests=9, maxRetryWaitTime=PT30S}, endpointDiscoveryEnabled=true, preferredRegions=[West US], multipleWriteRegionsEnabled=true, proxyType=null, inetSocketProxyAddress=null, readRequestsFallbackEnabled=true, connectTimeout=null, idleEndpointTimeout=null, maxConnectionsPerEndpoint=0, maxRequestsPerConnection=0}], consistencyLevel [Session], directModeProtocol [Tcp] [main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - creating a new shared HttpClient [parallel-1] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Getting database account endpoint from https://xxx.documents.azure.com:443 [main] INFO conCosmosDBv4 - The connection to Cosmos DB succeeded using GatewayMode. [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down ... [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Closing Global Endpoint Manager ... [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Closing StoreClientFactory ... [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down reactorHttpClient ... [main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - closing one reference to the shared HttpClient, the number of remaining references is 0 [main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - All references to shared HttpClient are closed. Closing the underlying HttpClient [main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down completed.
————————————
▼4. 参考情報
————————————
(1) Azure Cosmos DB を無料で試す
https://docs.microsoft.com/ja-jp/azure/cosmos-db/optimize-dev-test#try-azure-cosmos-db-for-free
(2) Connection policy: Use direct connection mode
https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-dotnet-sdk-v3-sql
(3) CosmosClientBuilder.gatewayMode Method
https://docs.microsoft.com/en-us/java/api/com.azure.cosmos.cosmosclientbuilder.gatewaymode?view=azure-java-stable
(4) CosmosClientBuilder.directMode Method
https://docs.microsoft.com/en-us/java/api/com.azure.cosmos.cosmosclientbuilder.directmode?view=azure-java-stable
以上です。参考になりましたら幸いです。