Simple Demo For Cosmos Change Feed while using MongoDB API
MongoDB natively has ChangeStream that is synonomous with Change Feed Of CosmosDB.
When using CosmosDB with MongoDB API, We can just use MongoDB Change Stream directly. We just have to be aware, the entire MongoDB ChangeStream functionalities may not be supported by CosmosDB. Check Limitations
In the Demo App, there are two Collections Employee & DuplicateEmployee. The App listens for ChangeFeed/ChangeStream messages on Employee Collection and inserts/updates the same Document into DuplicateEmployee Collection.
- Access To Azure CosmosDB
- Ensure MongoDB APi 3.6 version is used / enabled in Azure Portal
- Ensure MongoDB Aggregation Pipeline is enabled in Azure Portal
- Create New DB / Use Existing DB
- Create two Collections named Employee and DuplicateEmployee
- Rename src/main/resources/sample_application.properties to
application.properties
- Modify
src/main/resources/application.properties
to update MONGO URI and DB Name specific to your azure account
Reactive programming is a programming paradigm that deals with asynchronous data streams (sequences of events) and the specific propagation of change, which means it implements modifications to the execution environment (context) in a certain order. More Details Being Spring boot project uses Spring Reactive. This is used via below dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
- This is a typical Spring Boot APP. Run
com.gauri.cosmosdemo.Main
class. - Using Azure portal add a new Document to Employee Collection as per below structure. This App would have listened to changes in Employee Collection and inserted/updates a document in DuplicateEmployee Collection.
{
"_id": 4,
"name": "Gauri",
"department": "IT",
"designation": "Engg"
}
EmployeeChangeFeedListener.java sets up and subscribes to the ChangeStream of Employee Collection and acts to process the change (ie) inserting / updating same document in DuplicateEmployee Collection.
Few Rest Endpoints are powered by Demo App via TestServiceController.java Once Server is running, base path of the endpoints are http://localhost:8080/cosmosdemo/test
Path | Type | Functionality |
---|---|---|
http://localhost:8080/cosmosdemo/test/allEmployees | GET | Gets all Documents from Employee Collection |
http://localhost:8080/cosmosdemo/test/statusChangeFeedEmployee | GET | Gets the status of Employee Change Feed Subscription that informs, if the subscription is active |
http://localhost:8080/cosmosdemo/test/terminateChangeFeedEmployee | GET | Terminates the Employee Change Feed Subscription |
http://localhost:8080/cosmosdemo/test/insertEmployee | POST { "_id": 4, "name": "Gauri", "department": "IT", "designation": "Engg" } |
Insert a document into Employee Collection |