Search in sources :

Example 1 with CosmosAsyncClient

use of com.azure.cosmos.CosmosAsyncClient in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SalesOrder method TutorialSetUpAzureCosmosDBGlobalDistributionUsingTheSqlApiPreferredLocationsAsync.

/**
 * https://docs.microsoft.com/en-us/azure/cosmos-db/tutorial-global-distribution-sql-api
 * Tutorial: Set up Azure Cosmos DB global distribution using the SQL API
 */
/**
 * Preferred locations
 */
public static void TutorialSetUpAzureCosmosDBGlobalDistributionUsingTheSqlApiPreferredLocationsAsync() {
    String MASTER_KEY = "";
    String HOST = "";
    // <TutorialGlobalDistributionPreferredLocationAsync>
    ArrayList<String> preferredRegions = new ArrayList<String>();
    preferredRegions.add("East US");
    preferredRegions.add("West US");
    preferredRegions.add("Canada Central");
    CosmosAsyncClient client = new CosmosClientBuilder().endpoint(HOST).key(MASTER_KEY).preferredRegions(preferredRegions).contentResponseOnWriteEnabled(true).buildAsyncClient();
// </TutorialGlobalDistributionPreferredLocationAsync>
}
Also used : CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) ArrayList(java.util.ArrayList)

Example 2 with CosmosAsyncClient

use of com.azure.cosmos.CosmosAsyncClient in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SalesOrder method PerformanceTipsJavaSDKv4ConnectionModeAsync.

/**
 * https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java-sdk-v4-sql
 * Performance tips - async Connection Mode
 */
/**
 * Performance tips - async Connection Mode
 */
public static void PerformanceTipsJavaSDKv4ConnectionModeAsync() {
    String HOSTNAME = "";
    String MASTERKEY = "";
    // Arbitrary
    ConsistencyLevel CONSISTENCY = ConsistencyLevel.EVENTUAL;
    // <PerformanceClientConnectionModeAsync>
    /* Direct mode, default settings */
    CosmosAsyncClient clientDirectDefault = new CosmosClientBuilder().endpoint(HOSTNAME).key(MASTERKEY).consistencyLevel(CONSISTENCY).directMode().buildAsyncClient();
    /* Direct mode, custom settings */
    DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig();
    // Example config, do not use these settings as defaults
    directConnectionConfig.setMaxConnectionsPerEndpoint(120);
    directConnectionConfig.setIdleConnectionTimeout(Duration.ofMillis(100));
    CosmosAsyncClient clientDirectCustom = new CosmosClientBuilder().endpoint(HOSTNAME).key(MASTERKEY).consistencyLevel(CONSISTENCY).directMode(directConnectionConfig).buildAsyncClient();
    /* Gateway mode, default settings */
    CosmosAsyncClient clientGatewayDefault = new CosmosClientBuilder().endpoint(HOSTNAME).key(MASTERKEY).consistencyLevel(CONSISTENCY).gatewayMode().buildAsyncClient();
    /* Gateway mode, custom settings */
    GatewayConnectionConfig gatewayConnectionConfig = GatewayConnectionConfig.getDefaultConfig();
    // Example config, do not use these settings as defaults
    gatewayConnectionConfig.setProxy(new ProxyOptions(ProxyOptions.Type.HTTP, InetSocketAddress.createUnresolved("your.proxy.addr", 80)));
    gatewayConnectionConfig.setMaxConnectionPoolSize(150);
    CosmosAsyncClient clientGatewayCustom = new CosmosClientBuilder().endpoint(HOSTNAME).key(MASTERKEY).consistencyLevel(CONSISTENCY).gatewayMode(gatewayConnectionConfig).buildAsyncClient();
    /* No connection mode, defaults to Direct mode with default settings */
    CosmosAsyncClient clientDefault = new CosmosClientBuilder().endpoint(HOSTNAME).key(MASTERKEY).consistencyLevel(CONSISTENCY).buildAsyncClient();
// </PerformanceClientConnectionModeAsync>
}
Also used : ConsistencyLevel(com.azure.cosmos.ConsistencyLevel) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) DirectConnectionConfig(com.azure.cosmos.DirectConnectionConfig) ProxyOptions(com.azure.core.http.ProxyOptions) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) GatewayConnectionConfig(com.azure.cosmos.GatewayConnectionConfig)

Example 3 with CosmosAsyncClient

use of com.azure.cosmos.CosmosAsyncClient in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SalesOrder method MigrateJavaSDKv4ResourceAsync.

/**
 * https://docs.microsoft.com/en-us/azure/cosmos-db/migrate-java-v4-sdk
 * Migrate previous versions to Java SDK v4
 */
/**
 * Migrate previous versions to Java SDK v4
 */
public static void MigrateJavaSDKv4ResourceAsync() {
    String container_id = "family_container";
    String partition_key = "/pk";
    CosmosAsyncDatabase database = null;
    // <MigrateJavaSDKv4ResourceAsync>
    // Create Async client.
    // Building an async client is still a sync operation.
    CosmosAsyncClient client = new CosmosClientBuilder().endpoint("your.hostname").key("yourmasterkey").consistencyLevel(ConsistencyLevel.EVENTUAL).buildAsyncClient();
    // Create database with specified name
    client.createDatabaseIfNotExists("YourDatabaseName").flatMap(databaseResponse -> {
        testDatabaseAsync = client.getDatabase("YourDatabaseName");
        // Container properties - name and partition key
        CosmosContainerProperties containerProperties = new CosmosContainerProperties("YourContainerName", "/id");
        // Provision manual throughput
        ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400);
        // Create container
        return database.createContainerIfNotExists(containerProperties, throughputProperties);
    }).flatMap(containerResponse -> {
        testContainerAsync = database.getContainer("YourContainerName");
        return Mono.empty();
    }).subscribe();
// </MigrateJavaSDKv4ResourceAsync>
}
Also used : PartitionKey(com.azure.cosmos.models.PartitionKey) LoggerFactory(org.slf4j.LoggerFactory) ExcludedPath(com.azure.cosmos.models.ExcludedPath) Scheduler(reactor.core.scheduler.Scheduler) ArrayList(java.util.ArrayList) ProxyOptions(com.azure.core.http.ProxyOptions) DirectConnectionConfig(com.azure.cosmos.DirectConnectionConfig) Families(com.azure.cosmos.examples.common.Families) Family(com.azure.cosmos.examples.common.Family) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) CosmosStoredProcedureRequestOptions(com.azure.cosmos.models.CosmosStoredProcedureRequestOptions) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThroughputProperties(com.azure.cosmos.models.ThroughputProperties) Duration(java.time.Duration) Schedulers(reactor.core.scheduler.Schedulers) ConsistencyLevel(com.azure.cosmos.ConsistencyLevel) JsonNode(com.fasterxml.jackson.databind.JsonNode) CosmosItemRequestOptions(com.azure.cosmos.models.CosmosItemRequestOptions) ExecutorService(java.util.concurrent.ExecutorService) ChangeFeedProcessorBuilder(com.azure.cosmos.ChangeFeedProcessorBuilder) CustomPOJO(com.azure.cosmos.examples.common.CustomPOJO) CosmosContainerProperties(com.azure.cosmos.models.CosmosContainerProperties) CosmosStoredProcedureProperties(com.azure.cosmos.models.CosmosStoredProcedureProperties) IndexingPolicy(com.azure.cosmos.models.IndexingPolicy) Logger(org.slf4j.Logger) GatewayConnectionConfig(com.azure.cosmos.GatewayConnectionConfig) IncludedPath(com.azure.cosmos.models.IncludedPath) IndexingMode(com.azure.cosmos.models.IndexingMode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Mono(reactor.core.publisher.Mono) ChangeFeedProcessor(com.azure.cosmos.ChangeFeedProcessor) CosmosItemResponse(com.azure.cosmos.models.CosmosItemResponse) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Flux(reactor.core.publisher.Flux) List(java.util.List) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) ConflictResolutionPolicy(com.azure.cosmos.models.ConflictResolutionPolicy) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) ThroughputProperties(com.azure.cosmos.models.ThroughputProperties) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) CosmosContainerProperties(com.azure.cosmos.models.CosmosContainerProperties)

Example 4 with CosmosAsyncClient

use of com.azure.cosmos.CosmosAsyncClient in project testcontainers-java by testcontainers.

the class CosmosDBEmulatorContainerTest method testWithCosmosClient.

// }
@Test
public void testWithCosmosClient() throws Exception {
    // buildAndSaveNewKeyStore {
    Path keyStoreFile = tempFolder.newFile("azure-cosmos-emulator.keystore").toPath();
    KeyStore keyStore = emulator.buildNewKeyStore();
    keyStore.store(new FileOutputStream(keyStoreFile.toFile()), emulator.getEmulatorKey().toCharArray());
    // }
    // setSystemTrustStoreParameters {
    System.setProperty("javax.net.ssl.trustStore", keyStoreFile.toString());
    System.setProperty("javax.net.ssl.trustStorePassword", emulator.getEmulatorKey());
    System.setProperty("javax.net.ssl.trustStoreType", "PKCS12");
    // }
    // buildClient {
    CosmosAsyncClient client = new CosmosClientBuilder().gatewayMode().endpointDiscoveryEnabled(false).endpoint(emulator.getEmulatorEndpoint()).key(emulator.getEmulatorKey()).buildAsyncClient();
    // }
    // testWithClientAgainstEmulatorContainer {
    CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists("Azure").block();
    Assertions.assertThat(databaseResponse.getStatusCode()).isEqualTo(201);
    CosmosContainerResponse containerResponse = client.getDatabase("Azure").createContainerIfNotExists("ServiceContainer", "/name").block();
    Assertions.assertThat(containerResponse.getStatusCode()).isEqualTo(201);
// }
}
Also used : Path(java.nio.file.Path) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) CosmosDatabaseResponse(com.azure.cosmos.models.CosmosDatabaseResponse) FileOutputStream(java.io.FileOutputStream) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) KeyStore(java.security.KeyStore) CosmosContainerResponse(com.azure.cosmos.models.CosmosContainerResponse) Test(org.junit.Test)

Example 5 with CosmosAsyncClient

use of com.azure.cosmos.CosmosAsyncClient in project azure-cosmos-java-sql-api-samples by Azure-Samples.

the class SampleChangeFeedProcessor method main.

public static void main(String[] args) {
    logger.info("BEGIN Sample");
    try {
        // Summary of the next four commands:
        // -Create an asynchronous Azure Cosmos DB client and database so that we can issue async requests to the DB
        // -Create a "feed container" and a "lease container" in the DB
        logger.info("-->CREATE DocumentClient");
        CosmosAsyncClient client = getCosmosClient();
        logger.info("-->CREATE sample's database: " + DATABASE_NAME);
        CosmosAsyncDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME);
        logger.info("-->CREATE container for documents: " + COLLECTION_NAME);
        CosmosAsyncContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME);
        logger.info("-->CREATE container for lease: " + COLLECTION_NAME + "-leases");
        CosmosAsyncContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases");
        // Model of a worker thread or application which leases access to monitor one or more feed container
        // partitions via the Change Feed. In a real-world application you might deploy this code in an Azure function.
        // The next line causes the worker to create and start an instance of the Change Feed Processor. See the implementation of getChangeFeedProcessor() for guidance
        // on creating a handler for Change Feed events. In this stream, we also trigger the insertion of 10 documents on a separate
        // thread.
        logger.info("-->START Change Feed Processor on worker (handles changes asynchronously)");
        changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer);
        changeFeedProcessorInstance.start().subscribeOn(Schedulers.elastic()).doOnSuccess(aVoid -> {
        // pass
        }).subscribe();
        // These two lines model an application which is inserting ten documents into the feed container
        logger.info("-->START application that inserts documents into feed container");
        createNewDocumentsCustomPOJO(feedContainer, 10, Duration.ofSeconds(3));
        isWorkCompleted = true;
        // This loop models the Worker main loop, which spins while its Change Feed Processor instance asynchronously
        // handles incoming Change Feed events from the feed container. Of course in this sample, polling
        // isWorkCompleted is unnecessary because items are being added to the feed container on the same thread, and you
        // can see just above isWorkCompleted is set to true.
        // But conceptually the worker is part of a different thread or application than the one which is inserting
        // into the feed container; so this code illustrates the worker waiting and listening for changes to the feed container
        long remainingWork = WAIT_FOR_WORK;
        while (!isWorkCompleted && remainingWork > 0) {
            Thread.sleep(100);
            remainingWork -= 100;
        }
        // When all documents have been processed, clean up
        if (isWorkCompleted) {
            if (changeFeedProcessorInstance != null) {
                changeFeedProcessorInstance.stop().subscribe();
            }
        } else {
            throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time");
        }
        logger.info("-->DELETE sample's database: " + DATABASE_NAME);
        deleteDatabase(cosmosDatabase);
        Thread.sleep(500);
    } catch (Exception e) {
        e.printStackTrace();
    }
    logger.info("END Sample");
}
Also used : ChangeFeedProcessorBuilder(com.azure.cosmos.ChangeFeedProcessorBuilder) CosmosContainerProperties(com.azure.cosmos.models.CosmosContainerProperties) Logger(org.slf4j.Logger) Utils(com.azure.cosmos.implementation.Utils) CosmosContainerResponse(com.azure.cosmos.models.CosmosContainerResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) RandomStringUtils(com.azure.cosmos.implementation.apachecommons.lang.RandomStringUtils) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ChangeFeedProcessor(com.azure.cosmos.ChangeFeedProcessor) CosmosClientBuilder(com.azure.cosmos.CosmosClientBuilder) CosmosContainerRequestOptions(com.azure.cosmos.models.CosmosContainerRequestOptions) List(java.util.List) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) CosmosDatabaseResponse(com.azure.cosmos.models.CosmosDatabaseResponse) ThroughputProperties(com.azure.cosmos.models.ThroughputProperties) CustomPOJO2(com.azure.cosmos.examples.common.CustomPOJO2) Duration(java.time.Duration) Schedulers(reactor.core.scheduler.Schedulers) ConsistencyLevel(com.azure.cosmos.ConsistencyLevel) CosmosException(com.azure.cosmos.CosmosException) JsonNode(com.fasterxml.jackson.databind.JsonNode) CosmosAsyncContainer(com.azure.cosmos.CosmosAsyncContainer) CosmosAsyncClient(com.azure.cosmos.CosmosAsyncClient) CosmosAsyncDatabase(com.azure.cosmos.CosmosAsyncDatabase) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) CosmosException(com.azure.cosmos.CosmosException)

Aggregations

CosmosAsyncClient (com.azure.cosmos.CosmosAsyncClient)9 CosmosClientBuilder (com.azure.cosmos.CosmosClientBuilder)9 ConsistencyLevel (com.azure.cosmos.ConsistencyLevel)5 ProxyOptions (com.azure.core.http.ProxyOptions)3 DirectConnectionConfig (com.azure.cosmos.DirectConnectionConfig)3 GatewayConnectionConfig (com.azure.cosmos.GatewayConnectionConfig)3 ArrayList (java.util.ArrayList)3 ChangeFeedProcessor (com.azure.cosmos.ChangeFeedProcessor)2 ChangeFeedProcessorBuilder (com.azure.cosmos.ChangeFeedProcessorBuilder)2 CosmosAsyncContainer (com.azure.cosmos.CosmosAsyncContainer)2 CosmosAsyncDatabase (com.azure.cosmos.CosmosAsyncDatabase)2 CosmosContainerProperties (com.azure.cosmos.models.CosmosContainerProperties)2 CosmosContainerResponse (com.azure.cosmos.models.CosmosContainerResponse)2 CosmosDatabaseResponse (com.azure.cosmos.models.CosmosDatabaseResponse)2 ThroughputProperties (com.azure.cosmos.models.ThroughputProperties)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Duration (java.time.Duration)2 List (java.util.List)2