Skip to content

Commit 62fc8aa

Browse files
authored
Merge pull request #246110 from rinatmini/users/rinatmini/cfpsample
Refreshed Change Feed Processor example for Java SDK
2 parents 78d9824 + e02daf1 commit 62fc8aa

File tree

1 file changed

+26
-79
lines changed

1 file changed

+26
-79
lines changed

articles/cosmos-db/nosql/how-to-java-change-feed.md

Lines changed: 26 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -15,114 +15,61 @@ ms.custom: devx-track-java, ignite-2022, devx-track-extended-java
1515
# How to create a Java application that uses Azure Cosmos DB for NoSQL and change feed processor
1616
[!INCLUDE[NoSQL](../includes/appliesto-nosql.md)]
1717

18-
This how-to guide walks you through a simple Java application, which uses the Azure Cosmos DB for NoSQL to insert documents into an Azure Cosmos DB container, while maintaining a materialized view of the container using Change Feed and Change Feed Processor. The Java application communicates with the Azure Cosmos DB for NoSQL using Azure Cosmos DB Java SDK v4.
18+
Azure Cosmos DB is a fully managed NoSQL database service provided by Microsoft. It allows you to build globally distributed and highly scalable applications with ease. This how-to guide walks you through the process of creating a Java application that uses the Azure Cosmos DB for NoSQL database and implements the Change Feed Processor for real-time data processing. The Java application communicates with the Azure Cosmos DB for NoSQL using Azure Cosmos DB Java SDK v4.
1919

2020
> [!IMPORTANT]
21-
> This tutorial is for Azure Cosmos DB Java SDK v4 only. Please view the Azure Cosmos DB Java SDK v4 [Release notes](sdk-java-v4.md), [Maven repository](https://mvnrepository.com/artifact/com.azure/azure-cosmos), Azure Cosmos DB Java SDK v4 [performance tips](performance-tips-java-sdk-v4.md), and Azure Cosmos DB Java SDK v4 [troubleshooting guide](troubleshoot-java-sdk-v4.md) for more information. If you are currently using an older version than v4, see the [Migrate to Azure Cosmos DB Java SDK v4](migrate-java-v4-sdk.md) guide for help upgrading to v4.
21+
> This tutorial is for Azure Cosmos DB Java SDK v4 only. Please view the Azure Cosmos DB Java SDK v4 [Release notes](sdk-java-v4.md), [Maven repository](https://mvnrepository.com/artifact/com.azure/azure-cosmos), [Change feed processor in Azure Cosmos DB](change-feed-processor.md), and Azure Cosmos DB Java SDK v4 [troubleshooting guide](troubleshoot-java-sdk-v4.md) for more information. If you are currently using an older version than v4, see the [Migrate to Azure Cosmos DB Java SDK v4](migrate-java-v4-sdk.md) guide for help upgrading to v4.
2222
>
2323
2424
## Prerequisites
2525

26-
* The URI and key for your Azure Cosmos DB account
26+
* Azure Cosmos DB Account: you can create it from the [Azure portal](https://portal.azure.com/) or you can use [Azure Cosmos DB Emulator](../local-emulator.md) as well.
2727

28-
* Maven
28+
* Java Development Environment: Ensure you have Java Development Kit (JDK) installed on your machine with at least 8 version.
2929

30-
* Java 8
30+
* [Azure Cosmos DB Java SDK V4](sdk-java-v4.md): provides the necessary features to interact with Azure Cosmos DB.
3131

3232
## Background
3333

34-
The Azure Cosmos DB change feed provides an event-driven interface to trigger actions in response to document insertion. This has many uses. For example in applications, which are both read and write heavy, a chief use of change feed is to create a real-time **materialized view** of a container as it is ingesting documents. The materialized view container will hold the same data but partitioned for efficient reads, making the application both read and write efficient.
34+
The Azure Cosmos DB change feed provides an event-driven interface to trigger actions in response to document insertion that has many uses.
3535

3636
The work of managing change feed events is largely taken care of by the change feed Processor library built into the SDK. This library is powerful enough to distribute change feed events among multiple workers, if that is desired. All you have to do is provide the change feed library a callback.
3737

38-
This simple example demonstrates change feed Processor library with a single worker creating and deleting documents from a materialized view.
38+
This simple example of Java application is demonstrating real-time data processing with Azure Cosmos DB and the Change Feed Processor. The application inserts sample documents into a "feed container" to simulate a data stream. The Change Feed Processor, bound to the feed container, processes incoming changes and logs the document content. The processor automatically manages leases for parallel processing.
3939

40-
## Setup
40+
## Source code
4141

42-
If you haven't already done so, clone the app example repo:
42+
You can clone the SDK example repo and find this example in `SampleChangeFeedProcessor.java`:
4343

4444
```bash
45-
git clone https://github.com/Azure-Samples/azure-cosmos-java-sql-app-example.git
46-
```
47-
48-
Open a terminal in the repo directory. Build the app by running
49-
50-
```bash
51-
mvn clean package
45+
git clone https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples.git
46+
cd azure-cosmos-java-sql-api-sample/src/main/java/com/azure/cosmos/examples/changefeed/
5247
```
5348

5449
## Walkthrough
5550

56-
1. As a first check, you should have an Azure Cosmos DB account. Open the **Azure portal** in your browser, go to your Azure Cosmos DB account, and in the left pane navigate to **Data Explorer**.
57-
58-
:::image type="content" source="media/how-to-java-change-feed/cosmos_account_empty.JPG" alt-text="Azure Cosmos DB account":::
59-
60-
1. Run the app in the terminal using the following command:
61-
62-
```bash
63-
mvn exec:java -Dexec.mainClass="com.azure.cosmos.workedappexample.SampleGroceryStore" -DACCOUNT_HOST="your-account-uri" -DACCOUNT_KEY="your-account-key" -Dexec.cleanupDaemonThreads=false
64-
```
65-
66-
1. Press enter when you see
67-
68-
```bash
69-
Press enter to create the grocery store inventory system...
70-
```
71-
72-
then return to the Azure portal Data Explorer in your browser. You'll see a database **GroceryStoreDatabase** has been added with three empty containers:
73-
74-
* **InventoryContainer** - The inventory record for our example grocery store, partitioned on item ```id```, which is a UUID.
75-
* **InventoryContainer-pktype** - A materialized view of the inventory record, optimized for queries over item ```type```
76-
* **InventoryContainer-leases** - A leases container is always needed for change feed; leases track the app's progress in reading the change feed.
77-
78-
:::image type="content" source="media/how-to-java-change-feed/cosmos_account_resources_lease_empty.JPG" alt-text="Empty containers":::
79-
80-
1. In the terminal, you should now see a prompt
81-
82-
```bash
83-
Press enter to start creating the materialized view...
84-
```
85-
86-
Press enter. Now the following block of code will execute and initialize the change feed processor on another thread:
87-
88-
### <a id="java4-connection-policy-async"></a>Java SDK V4 (Maven com.azure::azure-cosmos) Async API
89-
90-
[!code-java[](~/azure-cosmos-java-sql-app-example/src/main/java/com/azure/cosmos/workedappexample/SampleGroceryStore.java?name=InitializeCFP)]
91-
92-
```"SampleHost_1"``` is the name of the Change Feed processor worker. ```changeFeedProcessorInstance.start()``` is what actually starts the Change Feed processor.
93-
94-
Return to the Azure portal Data Explorer in your browser. Under the **InventoryContainer-leases** container, select **items** to see its contents. You'll see that Change Feed Processor has populated the lease container, that is, the processor has assigned the ```SampleHost_1``` worker a lease on some partitions of the **InventoryContainer**.
95-
96-
:::image type="content" source="media/how-to-java-change-feed/cosmos_leases.JPG" alt-text="Leases":::
97-
98-
1. Press enter again in the terminal. This will trigger 10 documents to be inserted into **InventoryContainer**. Each document insertion appears in the change feed as JSON; the following callback code handles these events by mirroring the JSON documents into a materialized view:
99-
100-
### <a id="java4-connection-policy-async"></a>Java SDK V4 (Maven com.azure::azure-cosmos) Async API
101-
102-
[!code-java[](~/azure-cosmos-java-sql-app-example/src/main/java/com/azure/cosmos/workedappexample/SampleGroceryStore.java?name=CFPCallback)]
103-
104-
1. Allow the code to run 5-10 sec. Then return to the Azure portal Data Explorer and navigate to **InventoryContainer > items**. You should see that items are being inserted into the inventory container; note the partition key (```id```).
105-
106-
:::image type="content" source="media/how-to-java-change-feed/cosmos_items.JPG" alt-text="Feed container":::
51+
1. Configure the [`ChangeFeedProcessorOptions`](/java/api/com.azure.cosmos.models.changefeedprocessoroptions) in a Java application using Azure Cosmos DB and Azure Cosmos DB Java SDK V4. The [`ChangeFeedProcessorOptions`](/java/api/com.azure.cosmos.models.changefeedprocessoroptions) provides essential settings to control the behavior of the Change Feed Processor during data processing.
52+
[!code-java[](~/azure-cosmos-java-sql-api-samples/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java?name=ChangeFeedProcessorOptions)]
10753

108-
1. Now, in Data Explorer navigate to **InventoryContainer-pktype > items**. This is the materialized view - the items in this container mirror **InventoryContainer** because they were inserted programmatically by change feed. Note the partition key (```type```). So this materialized view is optimized for queries filtering over ```type```, which would be inefficient on **InventoryContainer** because it's partitioned on ```id```.
54+
2. Initialize [`ChangeFeedProcessor`](/java/api/com.azure.cosmos.changefeedprocessor) with relevant configurations, including the host name, feed container, lease container, and data handling logic. The [`start()`](/java/api/com.azure.cosmos.changefeedprocessor#com-azure-cosmos-changefeedprocessor-start()) method initiates the data processing, enabling concurrent and real-time processing of incoming data changes from the feed container.
55+
[!code-java[](~/azure-cosmos-java-sql-api-samples/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java?name=StartChangeFeedProcessor)]
10956

110-
:::image type="content" source="media/how-to-java-change-feed/cosmos_materializedview2.JPG" alt-text="Screenshot shows the Data Explorer page for an Azure Cosmos DB account with Items selected.":::
57+
3. Specify the delegate handles incoming data changes using the `handleChanges()` method. The method processes the received JsonNode documents from the Change Feed. As a developer you have two options for handling the JsonNode document provided to you by Change Feed. One option is to operate on the document in the form of a JsonNode. This is great especially if you don't have a single uniform data model for all documents. The second option - transform the JsonNode to a POJO having the same structure as the JsonNode. Then you can operate on the POJO.
58+
[!code-java[](~/azure-cosmos-java-sql-api-samples/src/main/java/com/azure/cosmos/examples/changefeed/SampleChangeFeedProcessor.java?name=Delegate)]
11159

112-
1. We're going to delete a document from both **InventoryContainer** and **InventoryContainer-pktype** using just a single ```upsertItem()``` call. First, take a look at Azure portal Data Explorer. We'll delete the document for which ```/type == "plums"```; it's encircled in red below
60+
4. Build and run the Java application. The application starts the Change Feed Processor, insert sample documents into the feed container, and process the incoming changes.
11361

114-
:::image type="content" source="media/how-to-java-change-feed/cosmos_materializedview-emph-todelete.JPG" alt-text="Screenshot shows the Data Explorer page for an Azure Cosmos DB account with a particular item ID selected.":::
62+
## Conclusion
11563

116-
Hit enter again to call the function ```deleteDocument()``` in the example code. This function, shown below, upserts a new version of the document with ```/ttl == 5```, which sets document Time-To-Live (TTL) to 5 sec.
117-
118-
### <a id="java4-connection-policy-async"></a>Java SDK V4 (Maven com.azure::azure-cosmos) Async API
64+
In this guide, you learned how to create a Java application using [Azure Cosmos DB Java SDK V4](sdk-java-v4.md) that uses the Azure Cosmos DB for NoSQL database and uses the Change Feed Processor for real-time data processing. You can extend this application to handle more complex use cases and build robust, scalable, and globally distributed applications using Azure Cosmos DB.
11965

120-
[!code-java[](~/azure-cosmos-java-sql-app-example/src/main/java/com/azure/cosmos/workedappexample/SampleGroceryStore.java?name=DeleteWithTTL)]
66+
## Additional resources
12167

122-
The change feed ```feedPollDelay``` is set to 100 ms; therefore, change feed responds to this update almost instantly and calls ```updateInventoryTypeMaterializedView()``` shown above. That last function call will upsert the new document with TTL of 5 sec into **InventoryContainer-pktype**.
68+
* [Azure Cosmos DB Java SDK V4](sdk-java-v4.md)
69+
* [Additional samples on GitHub](https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples)
12370

124-
The effect is that after about 5 seconds, the document will expire and be deleted from both containers.
71+
## Next steps
12572

126-
This procedure is necessary because change feed only issues events on item insertion or update, not on item deletion.
73+
You can now proceed to learn more about change feed estimator in the following articles:
12774

128-
1. Press enter one more time to close the program and clean up its resources.
75+
* [Use the change feed estimator](how-to-use-change-feed-estimator.md)

0 commit comments

Comments
 (0)