다음을 통해 공유


CosmosClientBuilder Class

  • java.lang.Object
    • com.azure.cosmos.CosmosClientBuilder

Implements

public class CosmosClientBuilder
implements TokenCredentialTrait<CosmosClientBuilder>, AzureKeyCredentialTrait<CosmosClientBuilder>, EndpointTrait<CosmosClientBuilder>

Helper class to build CosmosAsyncClient and CosmosClient instances as logical representation of the Azure Cosmos database service.

CosmosAsyncClient and CosmosClient are thread-safe. It's recommended to maintain a single instance of CosmosClient or CosmosAsyncClient per lifetime of the application which enables efficient connection management and performance. CosmosAsyncClient and CosmosClient initializations are heavy operations - don't use initialization CosmosAsyncClient or CosmosClient instances as credentials or network connectivity validations.

When building client, endpoint() and key() are mandatory APIs, without these the initialization will fail.

Though consistencyLevel is not mandatory, but we strongly suggest to pay attention to this API when building client. By default, account consistency level is used if none is provided.

By default, direct connection mode is used if none specified.

Building Cosmos Async Client minimal APIs (without any customized configurations)
 
 CosmosAsyncClient client = new CosmosClientBuilder()
         .endpoint(serviceEndpoint)
         .key(key)
         .buildAsyncClient();
Building Cosmos Async Client with customizations
 
 CosmosAsyncClient client = new CosmosClientBuilder()
         .endpoint(serviceEndpoint)
         .key(key)
         .directMode(directConnectionConfig, gatewayConnectionConfig)
         .consistencyLevel(ConsistencyLevel.SESSION)
         .connectionSharingAcrossClientsEnabled(true)
         .contentResponseOnWriteEnabled(true)
         .userAgentSuffix("my-application1-client")
         .preferredRegions(Collections.singletonList("West US", "East US"))
         .buildAsyncClient();
Building Cosmos Sync Client minimal APIs (without any customized configurations)
 
 CosmosClient client = new CosmosClientBuilder()
         .endpoint(serviceEndpoint)
         .key(key)
         .buildClient();
Building Cosmos Sync Client with customizations
 
 CosmosClient client = new CosmosClientBuilder()
         .endpoint(serviceEndpoint)
         .key(key)
         .directMode(directConnectionConfig, gatewayConnectionConfig)
         .consistencyLevel(ConsistencyLevel.SESSION)
         .connectionSharingAcrossClientsEnabled(true)
         .contentResponseOnWriteEnabled(true)
         .userAgentSuffix("my-application1-client")
         .preferredRegions(Collections.singletonList("West US", "East US"))
         .buildClient();

Constructor Summary

Constructor Description
CosmosClientBuilder()

Instantiates a new Cosmos client builder.

Method Summary

Modifier and Type Method and Description
CosmosClientBuilder addOperationPolicy(CosmosOperationPolicy policy)

Adds a policy for modifying request options dynamically.

CosmosClientBuilder authorizationTokenResolver(CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver)

Sets the token resolver

CosmosAsyncClient buildAsyncClient()

Builds a cosmos async client with the provided properties

CosmosClient buildClient()

Builds a cosmos sync client with the provided properties

CosmosClientBuilder clientTelemetryConfig(CosmosClientTelemetryConfig telemetryConfig)

Returns the client telemetry config instance for this builder

CosmosClientBuilder clientTelemetryEnabled(boolean clientTelemetryEnabled)

Sets the flag to enable client telemetry which will periodically collect database operations aggregation statistics, system information like cpu/memory and send it to cosmos monitoring service, which will be helpful during debugging.

CosmosClientBuilder connectionSharingAcrossClientsEnabled(boolean connectionSharingAcrossClientsEnabled)

Enables connections sharing across multiple Cosmos Clients.

CosmosClientBuilder consistencyLevel(ConsistencyLevel desiredConsistencyLevel)

Sets the ConsistencyLevel to be used By default, SESSION consistency will be used.

CosmosClientBuilder contentResponseOnWriteEnabled(boolean contentResponseOnWriteEnabled)

Sets the boolean to only return the headers and status code in Cosmos DB response in case of Create, Update and Delete operations on CosmosItem.

CosmosClientBuilder credential(AzureKeyCredential credential)

Sets the AzureKeyCredential to be used

CosmosClientBuilder credential(TokenCredential credential)

Sets the TokenCredential used to authorize requests sent to the service.

CosmosClientBuilder customItemSerializer(CosmosItemSerializer customItemSerializer)

Sets a custom serializer that should be used for conversion between POJOs and Json payload stored in the Cosmos DB service.

CosmosClientBuilder directMode()

Sets the default DIRECT connection configuration to be used.

CosmosClientBuilder directMode(DirectConnectionConfig directConnectionConfig)

Sets the DIRECT connection configuration to be used.

CosmosClientBuilder directMode(DirectConnectionConfig directConnectionConfig, GatewayConnectionConfig gatewayConnectionConfig)

Sets the DIRECT connection configuration to be used.

CosmosClientBuilder endToEndOperationLatencyPolicyConfig(CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig)

Sets the CosmosEndToEndOperationLatencyPolicyConfig on the client

CosmosClientBuilder endpoint(String endpoint)

Sets the Azure Cosmos DB endpoint the SDK will connect to

CosmosClientBuilder endpointDiscoveryEnabled(boolean endpointDiscoveryEnabled)

Sets the flag to enable endpoint discovery for geo-replicated database accounts.

CosmosClientBuilder excludedRegionsSupplier(Supplier<CosmosExcludedRegions> excludedRegionsSupplier)

Sets a Supplier which returns a CosmosExcludedRegions instance when Supplier#get() is invoked.

CosmosClientBuilder gatewayMode()

Sets the default GATEWAY connection configuration to be used.

CosmosClientBuilder gatewayMode(GatewayConnectionConfig gatewayConnectionConfig)

Sets the GATEWAY connection configuration to be used.

CosmosClientBuilder key(String key)

Sets either a master or readonly key used to perform authentication for accessing resource.

CosmosClientBuilder multipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled)

Sets the flag to enable writes on any regions for geo-replicated database accounts in the Azure Cosmos DB service.

CosmosClientBuilder nonIdempotentWriteRetryOptions(NonIdempotentWriteRetryOptions options)

Enables automatic retries for write operations even when the SDK can't guarantee that they are idempotent.

CosmosClientBuilder openConnectionsAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig)

Sets the CosmosContainerProactiveInitConfig which enable warming up of caches and connections associated with containers obtained from getCosmosContainerIdentities() to replicas obtained from the first k preferred regions where k evaluates to getProactiveConnectionRegionsCount().

CosmosClientBuilder permissions(List<CosmosPermissionProperties> permissions)

Sets the permission list, which contains the resource tokens needed to access resources.

CosmosClientBuilder preferredRegions(List<String> preferredRegions)

Sets the preferred regions for geo-replicated database accounts.

CosmosClientBuilder readRequestsFallbackEnabled(boolean readRequestsFallbackEnabled)

Sets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service.

CosmosClientBuilder resourceToken(String resourceToken)

Sets a resource token used to perform authentication for accessing resource.

CosmosClientBuilder sessionCapturingOverrideEnabled(boolean sessionCapturingOverrideEnabled)

Session capturing is enabled by default for SESSION.

CosmosClientBuilder sessionRetryOptions(SessionRetryOptions sessionRetryOptions)

Sets the SessionRetryOptions instance on the client.

CosmosClientBuilder throttlingRetryOptions(ThrottlingRetryOptions throttlingRetryOptions)

Sets the retry policy options associated with the DocumentClient instance.

CosmosClientBuilder userAgentSuffix(String userAgentSuffix)

sets the value of the user-agent suffix.

Methods inherited from java.lang.Object

Constructor Details

CosmosClientBuilder

public CosmosClientBuilder()

Instantiates a new Cosmos client builder.

Method Details

addOperationPolicy

public CosmosClientBuilder addOperationPolicy(CosmosOperationPolicy policy)

Adds a policy for modifying request options dynamically. The last policy defined aimed towards the same operation type will be the one ultimately applied.

Parameters:

policy - the policy to add

Returns:

current cosmosClientBuilder

authorizationTokenResolver

public CosmosClientBuilder authorizationTokenResolver(CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver)

Sets the token resolver

Parameters:

cosmosAuthorizationTokenResolver - the token resolver

Returns:

current cosmosClientBuilder

buildAsyncClient

public CosmosAsyncClient buildAsyncClient()

Builds a cosmos async client with the provided properties

Returns:

CosmosAsyncClient

buildClient

public CosmosClient buildClient()

Builds a cosmos sync client with the provided properties

Returns:

CosmosClient

clientTelemetryConfig

public CosmosClientBuilder clientTelemetryConfig(CosmosClientTelemetryConfig telemetryConfig)

Returns the client telemetry config instance for this builder

Parameters:

telemetryConfig - the client telemetry configuration to be used

Returns:

current CosmosClientBuilder

clientTelemetryEnabled

public CosmosClientBuilder clientTelemetryEnabled(boolean clientTelemetryEnabled)

Sets the flag to enable client telemetry which will periodically collect database operations aggregation statistics, system information like cpu/memory and send it to cosmos monitoring service, which will be helpful during debugging.

DEFAULT value is false indicating this is opt in feature, by default no telemetry collection.

Parameters:

clientTelemetryEnabled - flag to enable client telemetry.

Returns:

current CosmosClientBuilder

connectionSharingAcrossClientsEnabled

public CosmosClientBuilder connectionSharingAcrossClientsEnabled(boolean connectionSharingAcrossClientsEnabled)

Enables connections sharing across multiple Cosmos Clients. The default is false.

CosmosAsyncClient client1 = new CosmosClientBuilder()
         .endpoint(serviceEndpoint1)
         .key(key1)
         .consistencyLevel(ConsistencyLevel.SESSION)
         .connectionSharingAcrossClientsEnabled(true)
         .buildAsyncClient();

 CosmosAsyncClient client2 = new CosmosClientBuilder()
         .endpoint(serviceEndpoint2)
         .key(key2)
         .consistencyLevel(ConsistencyLevel.SESSION)
         .connectionSharingAcrossClientsEnabled(true)
         .buildAsyncClient();

 // when configured this way client1 and client2 will share connections when possible.

When you have multiple instances of Cosmos Client in the same JVM interacting to multiple Cosmos accounts, enabling this allows connection sharing in Direct mode if possible between instances of Cosmos Client. Please note, when setting this option, the connection configuration (e.g., socket timeout config, idle timeout config) of the first instantiated client will be used for all other client instances.

Parameters:

connectionSharingAcrossClientsEnabled - connection sharing

Returns:

current cosmosClientBuilder

consistencyLevel

public CosmosClientBuilder consistencyLevel(ConsistencyLevel desiredConsistencyLevel)

Sets the ConsistencyLevel to be used By default, SESSION consistency will be used.

Parameters:

desiredConsistencyLevel - ConsistencyLevel

Returns:

current Builder

contentResponseOnWriteEnabled

public CosmosClientBuilder contentResponseOnWriteEnabled(boolean contentResponseOnWriteEnabled)

Sets the boolean to only return the headers and status code in Cosmos DB response in case of Create, Update and Delete operations on CosmosItem. If set to false (which is by default), service doesn't return payload in the response. It reduces networking and CPU load by not sending the payload back over the network and serializing it on the client. This feature does not impact RU usage for read or write operations. By-default, this is false.

Parameters:

contentResponseOnWriteEnabled - a boolean indicating whether payload will be included in the response or not

Returns:

current cosmosClientBuilder

credential

public CosmosClientBuilder credential(AzureKeyCredential credential)

Sets the AzureKeyCredential to be used

Parameters:

credential - AzureKeyCredential

Returns:

current cosmosClientBuilder

credential

public CosmosClientBuilder credential(TokenCredential credential)

Sets the TokenCredential used to authorize requests sent to the service. Refer to the Azure SDK for Java identity and authentication documentation for more details on proper usage of the TokenCredential type.

Parameters:

credential - TokenCredential used to authorize requests sent to the service.

Returns:

the updated CosmosClientBuilder

customItemSerializer

public CosmosClientBuilder customItemSerializer(CosmosItemSerializer customItemSerializer)

Sets a custom serializer that should be used for conversion between POJOs and Json payload stored in the Cosmos DB service. The custom serializer can also be specified in request options. If defined here and in request options the serializer defined in request options will be used.

Parameters:

customItemSerializer - the custom serializer to be used for item payload transformations

Returns:

current CosmosClientBuilder

directMode

public CosmosClientBuilder directMode()

Sets the default DIRECT connection configuration to be used. By default, the builder is initialized with directMode()

Returns:

current CosmosClientBuilder

directMode

public CosmosClientBuilder directMode(DirectConnectionConfig directConnectionConfig)

Sets the DIRECT connection configuration to be used. By default, the builder is initialized with directMode()

Parameters:

directConnectionConfig - direct connection configuration

Returns:

current CosmosClientBuilder

directMode

public CosmosClientBuilder directMode(DirectConnectionConfig directConnectionConfig, GatewayConnectionConfig gatewayConnectionConfig)

Sets the DIRECT connection configuration to be used. gatewayConnectionConfig - represents basic configuration to be used for gateway client. Even in direct connection mode, some of the meta data operations go through gateway client, Setting gateway connection config in this API doesn't affect the connection mode, which will be Direct in this case.

Parameters:

directConnectionConfig - direct connection configuration to be used
gatewayConnectionConfig - gateway connection configuration to be used

Returns:

current CosmosClientBuilder

endToEndOperationLatencyPolicyConfig

public CosmosClientBuilder endToEndOperationLatencyPolicyConfig(CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig)

Sets the CosmosEndToEndOperationLatencyPolicyConfig on the client

Parameters:

cosmosEndToEndOperationLatencyPolicyConfig - the CosmosEndToEndOperationLatencyPolicyConfig

Returns:

current CosmosClientBuilder

endpoint

public CosmosClientBuilder endpoint(String endpoint)

Sets the Azure Cosmos DB endpoint the SDK will connect to

Parameters:

endpoint - the service endpoint

Returns:

current Builder

endpointDiscoveryEnabled

public CosmosClientBuilder endpointDiscoveryEnabled(boolean endpointDiscoveryEnabled)

Sets the flag to enable endpoint discovery for geo-replicated database accounts.

When EnableEndpointDiscovery is true, the SDK will automatically discover the current write and read regions to ensure requests are sent to the correct region based on the capability of the region and the user's preference.

The default value for this property is true indicating endpoint discovery is enabled.

Parameters:

endpointDiscoveryEnabled - true if EndpointDiscovery is enabled.

Returns:

current CosmosClientBuilder

excludedRegionsSupplier

public CosmosClientBuilder excludedRegionsSupplier(Supplier excludedRegionsSupplier)

Sets a Supplier which returns a CosmosExcludedRegions instance when Supplier#get() is invoked. The request will not be routed to regions present in getExcludedRegions() for hedging scenarios and retry scenarios for the workload executed through this instance of CosmosClient / CosmosAsyncClient.

Parameters:

excludedRegionsSupplier - the supplier which returns a CosmosExcludedRegions instance.

Returns:

current CosmosClientBuilder.

gatewayMode

public CosmosClientBuilder gatewayMode()

Sets the default GATEWAY connection configuration to be used.

Returns:

current CosmosClientBuilder

gatewayMode

public CosmosClientBuilder gatewayMode(GatewayConnectionConfig gatewayConnectionConfig)

Sets the GATEWAY connection configuration to be used.

Parameters:

gatewayConnectionConfig - gateway connection configuration

Returns:

current CosmosClientBuilder

key

public CosmosClientBuilder key(String key)

Sets either a master or readonly key used to perform authentication for accessing resource.

Parameters:

key - master or readonly key

Returns:

current Builder.

multipleWriteRegionsEnabled

public CosmosClientBuilder multipleWriteRegionsEnabled(boolean multipleWriteRegionsEnabled)

Sets the flag to enable writes on any regions for geo-replicated database accounts in the Azure Cosmos DB service.

When the value of this property is true, the SDK will direct write operations to available writable regions of geo-replicated database account. Writable regions are ordered by PreferredRegions property. Setting the property value to true has no effect until EnableMultipleWriteRegions in DatabaseAccount is also set to true.

DEFAULT value is true indicating that writes are directed to available writable regions of geo-replicated database account.

Parameters:

multipleWriteRegionsEnabled - flag to enable writes on any regions for geo-replicated database accounts.

Returns:

current CosmosClientBuilder

nonIdempotentWriteRetryOptions

public CosmosClientBuilder nonIdempotentWriteRetryOptions(NonIdempotentWriteRetryOptions options)

Enables automatic retries for write operations even when the SDK can't guarantee that they are idempotent. This is the default behavior for the entire Cosmos client - the policy can be overridden for individual operations in the request options.

NOTE: the setting on the CosmosClientBuilder will determine the default behavior for Create, Replace, Upsert and Delete operations. It can be overridden on per-request base in the request options. For patch operations by default (unless overridden in the request options) retries are always disabled by default. - Create: retries can result in surfacing (more) 409-Conflict requests to the application when a retry tries to create a document that the initial attempt successfully created. When enabling useTrackingIdPropertyForCreateAndReplace this can be avoided for 409-Conflict caused by retries. - Replace: retries can result in surfacing (more) 412-Precondition failure requests to the application when a replace operations are using a pre-condition check (etag) and a retry tries to update a document that the initial attempt successfully updated (causing the etag to change). When enabling useTrackingIdPropertyForCreateAndReplace this can be avoided for 412-Precondition failures caused by retries. - Delete: retries can result in surfacing (more) 404-NotFound requests when a delete operation is retried and the initial attempt succeeded. Ideally, write retries should only be enabled when applications can gracefully handle 404 - Not Found. - Upsert: retries can result in surfacing a 200 - looking like the document was updated when actually the document has been created by the initial attempt - so logically within the same operation. This will only impact applications who have special casing for 201 vs. 200 for upsert operations. Patch: retries for patch can but will not always be idempotent - it completely depends on the patch operations being executed and the precondition filters being used. Before enabling write retries for patch this needs to be carefully reviewed and tests - which is wht retries for patch can only be enabled on request options - any CosmosClient wide configuration will be ignored. Bulk/Delete by PK/Transactional Batch/Stored Procedure execution: No automatic retries are supported.

Parameters:

options - the options controlling whether non-idempotent write operations should be retried and whether trackingIds can be used.

Returns:

the CosmosItemRequestOptions

openConnectionsAndInitCaches

public CosmosClientBuilder openConnectionsAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig)

Sets the CosmosContainerProactiveInitConfig which enable warming up of caches and connections associated with containers obtained from getCosmosContainerIdentities() to replicas obtained from the first k preferred regions where k evaluates to getProactiveConnectionRegionsCount().

Use the CosmosContainerProactiveInitConfigBuilder class to instantiate CosmosContainerProactiveInitConfig class

Parameters:

proactiveContainerInitConfig - which encapsulates a list of container identities and no of proactive connection regions

Returns:

current CosmosClientBuilder

permissions

public CosmosClientBuilder permissions(List permissions)

Sets the permission list, which contains the resource tokens needed to access resources.

Parameters:

permissions - Permission list for authentication.

Returns:

current Builder.

preferredRegions

public CosmosClientBuilder preferredRegions(List preferredRegions)

Sets the preferred regions for geo-replicated database accounts. For example, "East US" as the preferred region.

When EnableEndpointDiscovery is true and PreferredRegions is non-empty, the SDK will prefer to use the regions in the container in the order they are specified to perform operations.

If EnableEndpointDiscovery is set to false, this property is ignored.

Parameters:

preferredRegions - the list of preferred regions.

Returns:

current CosmosClientBuilder

readRequestsFallbackEnabled

public CosmosClientBuilder readRequestsFallbackEnabled(boolean readRequestsFallbackEnabled)

Sets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service.

DEFAULT value is true.

If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, The default is false for Bounded Staleness. 1. #endpointDiscoveryEnabled is true 2. the Azure Cosmos DB account has more than one region

Parameters:

readRequestsFallbackEnabled - flag to enable reads to go to multiple regions configured on an account of Azure Cosmos DB service.

Returns:

current CosmosClientBuilder

resourceToken

public CosmosClientBuilder resourceToken(String resourceToken)

Sets a resource token used to perform authentication for accessing resource.

Parameters:

resourceToken - resourceToken for authentication

Returns:

current Builder.

sessionCapturingOverrideEnabled

public CosmosClientBuilder sessionCapturingOverrideEnabled(boolean sessionCapturingOverrideEnabled)

Session capturing is enabled by default for SESSION. For other consistency levels, it is not needed, unless if you need occasionally send requests with Session Consistency while the client is not configured in session.

enabling Session capturing for Session mode has no effect.

Parameters:

sessionCapturingOverrideEnabled - session capturing override

Returns:

current cosmosClientBuilder

sessionRetryOptions

public CosmosClientBuilder sessionRetryOptions(SessionRetryOptions sessionRetryOptions)

Sets the SessionRetryOptions instance on the client.

This setting helps in optimizing retry behavior associated with NOT_FOUND / READ_SESSION_NOT_AVAILABLE or 404 / 1002 scenarios which happen when the targeted consistency used by the request is Session Consistency and a request goes to a region that does not have recent enough data which the request is looking for.

DISCLAIMER: Setting SessionRetryOptions will modify retry behavior for all operations or workloads executed through this instance of the client.

For multi-write accounts:

  • For a read request going to a local read region, it is possible to optimize availability by having the request be retried on a different write region since the other write region might have more upto date data.
  • For a read request going to a local write region, it could help to switch to a different write region right away provided the local write region does not have the most up to date data.
  • For a write request going to a local write region, it could help to switch to a different write region right away provided the local write region does not have the most up to date data.

For single-write accounts:

  • If a read request goes to a local read region, it helps to switch to the write region quicker.
  • If a read request goes to a write region, the SessionRetryOptions setting does not matter since the write region in a single-write account has the most up to date data.
  • For a write to a write region in a single-write account, READ_SESSION_NOT_AVAILABLE errors do not apply since the write-region always has the most recent version of the data and all writes go to the primary replica in this region. Therefore, replication lags causing errors is not applicable here.

About region switch hints:

Operations supported:

  • Read
  • Query
  • Create
  • Replace
  • Upsert
  • Delete
  • Patch
  • Batch
  • Bulk

Parameters:

sessionRetryOptions - The SessionRetryOptions instance.

Returns:

current CosmosClientBuilder

throttlingRetryOptions

public CosmosClientBuilder throttlingRetryOptions(ThrottlingRetryOptions throttlingRetryOptions)

Sets the retry policy options associated with the DocumentClient instance.

Properties in the RetryOptions class allow application to customize the built-in retry policies. This property is optional. When it's not set, the SDK uses the default values for configuring the retry policies. See RetryOptions class for more details.

Parameters:

throttlingRetryOptions - the RetryOptions instance.

Returns:

current CosmosClientBuilder

userAgentSuffix

public CosmosClientBuilder userAgentSuffix(String userAgentSuffix)

sets the value of the user-agent suffix.

Parameters:

userAgentSuffix - The value to be appended to the user-agent header, this is used for monitoring purposes.

Returns:

current CosmosClientBuilder

Applies to