private static final String ENDPOINT_URI = "https://<your-cosmosdb-account-name>.documents.azure.com:443/";
private static final String PRIMARY_KEY = "<your-cosmosdb-primary-key>";
private static final String DATABASE_NAME = "<your-cosmosdb-database-name>";
private static final String COLLECTION_NAME = "<your-cosmosdb-collection-name>";
public static void main(String[] args) throws DocumentClientException, InterruptedException {
DocumentClient documentClient = new DocumentClient(ENDPOINT_URI, PRIMARY_KEY, ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
FeedOptions feedOptions = new FeedOptions();
feedOptions.setMaxItemCount(100);
feedOptions.setPartitionKeyRangeId("0");
feedOptions.setEnableCrossPartitionQuery(true);
// Query the collection for partition key ranges
FeedResponse<PartitionKeyRange> response = documentClient.readPartitionKeyRangeFeed(
String.format("/dbs/%s/colls/%s/pkranges", DATABASE_NAME, COLLECTION_NAME), feedOptions);
// Create the ChangeFeedProcessor instance
ChangeFeedProcessor changeFeedProcessor = new ChangeFeedProcessorBuilder()
.hostName("your-change-feed-processor-host-name")
.feedCollection(documentClient, DATABASE_NAME, COLLECTION_NAME)
.checkpointStoreCollection(documentClient, DATABASE_NAME, "your-checkpoint-store-collection-name")
.handleChanges((docs, context) -> {
for (Document doc : docs) {
System.out.println("Received document change: " + doc.toJson());
}
})
.build();
// Start the change feed processor
changeFeedProcessor.start();
}
}
In this code, the DocumentClient class is used to connect to the Cosmos DB database, and the ChangeFeedProcessor class is used to process the Change Feed of the database. The code defines a handler that is called for each set of changes to the database, and it simply prints the JSON representation of each changed document to the console.