How do you split events in a Kafka topic so that the events are placed into subtopics?
Example use case:
Suppose that you have a Kafka topic representing appearances of an actor or actress in a film, with each event denoting the genre. In this tutorial, we'll write a program that splits the stream into substreams based on the genre. We'll have a topic for drama films, a topic for fantasy films, and a topic for everything else. Related pattern: Event Router.
Use the split() and branch() method, see below. Notice the last predicate which simply returns true, which acts as an "else" statement to catch all events that don’t match the other predicates.
To get started, make a new directory anywhere you’d like for this project:
mkdir split-stream && cd split-stream
Next, create a directory for configuration data:
mkdir configuration
Provision your Kafka cluster
2
This tutorial requires access to an Apache Kafka cluster, and the quickest way to get started free is on Confluent Cloud, which provides Kafka as a fully managed service.
After you log in to Confluent Cloud, click Environments in the lefthand navigation, click on Add cloud environment, and name the environment learn-kafka. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.
From the Billing & payment section in the menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details). To avoid having to enter a credit card, add an additional promo code CONFLUENTDEV1. With this promo code, you will not have to enter a credit card for 30 days or until your credits run out.
Click on LEARN and follow the instructions to launch a Kafka cluster and enable Schema Registry.
Write the cluster information into a local file
3
From the Confluent Cloud Console, navigate to your Kafka cluster and then select Clients in the lefthand navigation. From the Clients view, create a new client and click Java to get the connection information customized to your cluster.
Create new credentials for your Kafka cluster and Schema Registry, writing in appropriate descriptions so that the keys are easy to find and delete later. The Confluent Cloud Console will show a configuration similar to below with your new credentials automatically populated (make sure Show API keys is checked).
Copy and paste it into a configuration/ccloud.properties file on your machine.
# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username='{{ CLUSTER_API_KEY }}' password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips
# Best practice for Kafka producer to prevent data loss
acks=all
# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url={{ SR_URL }}
basic.auth.credentials.source=USER_INFO
basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}
Do not directly copy and paste the above configuration. You must copy it from the Confluent Cloud Console so that it includes your Confluent Cloud information and credentials.
Download and set up the Confluent CLI
4
This tutorial has some steps for Kafka topic management and producing and consuming events, for which you can use the Confluent Cloud Console or the Confluent CLI. Follow the instructions here to install the Confluent CLI, and then follow these steps connect the CLI to your Confluent Cloud cluster.
Configure the project
5
Then create the following Gradle build file, named build.gradle for the project:
Update the properties file with Confluent Cloud information
6
Using the command below, append the contents of configuration/ccloud.properties (with your Confluent Cloud configuration) to configuration/dev.properties (with the application properties).
Because we will use this Avro schema in our Java code, we’ll need to compile it. Run the following:
./gradlew build
Create the Kafka Streams topology
8
Create a directory for the Java files in this project:
mkdir -p src/main/java/io/confluent/developer
Then create the following file at src/main/java/io/confluent/developer/SplitStream.java. Notice the buildTopology method, which uses the Kafka Streams DSL. By using the split and Branched methods, which are stateless record-by-record operations, you can create branches for messages that match the predicate. If no predicates are matched, the event gets dropped from further processing, but in this case, notice the last predicate, which simply returns true. This acts as an "else" statement to catch all events that don’t match the other predicates.
KIP-418 for details on method-chaining to branch a KStream.
Now that an uberjar for the Kafka Streams application has been built, you can launch it locally. When you run the following, the prompt won’t return, because the application will run until you exit it:
confluent kafka topic produce acting-events --value-format avro --schema src/main/avro/acting_event.avsc
You will be prompted for the Confluent Cloud Schema Registry credentials as shown below, which you can find in the configuration/ccloud.properties configuration file.
Look for the configuration parameter basic.auth.user.info, whereby the ":" is the delimiter between the key and secret.
Enter your Schema Registry API key:
Enter your Schema Registry API secret:
When the console producer starts, it will log some messages and hang, waiting for your input. Type in one line at a time and press enter to send it. Each line represents an event. To send all of the events below, paste the following into the prompt and press enter:
{"name": "Meryl Streep", "title": "The Iron Lady", "genre": "drama"}
{"name": "Will Smith", "title": "Men in Black", "genre": "comedy"}
{"name": "Matt Damon", "title": "The Martian", "genre": "drama"}
{"name": "Judy Garland", "title": "The Wizard of Oz", "genre": "fantasy"}
{"name": "Jennifer Aniston", "title": "Office Space", "genre": "comedy"}
{"name": "Bill Murray", "title": "Ghostbusters", "genre": "fantasy"}
{"name": "Christian Bale", "title": "The Dark Knight", "genre": "crime"}
{"name": "Laura Dern", "title": "Jurassic Park", "genre": "fantasy"}
{"name": "Keanu Reeves", "title": "The Matrix", "genre": "fantasy"}
{"name": "Russell Crowe", "title": "Gladiator", "genre": "drama"}
{"name": "Diane Keaton", "title": "The Godfather: Part II", "genre": "crime"}
Consume the event subsets from the output topics
11
Leave your original terminal running. To consume the output events from each of the topic, you’ll need to open several new terminal windows. In each instance, the prompt will hang, waiting for more events to arrive. To continue studying the example, send more events through the input terminal prompt. Otherwise, you can Control-C to exit the process.
First, to consume the events of drama films, run the following:
{"name":"Will Smith","title":"Men in Black","genre":"comedy"}
{"name":"Jennifer Aniston","title":"Office Space","genre":"comedy"}
{"name":"Christian Bale","title":"The Dark Knight","genre":"crime"}
{"name":"Diane Keaton","title":"The Godfather: Part II","genre":"crime"}
Teardown Confluent Cloud resources
12
You may try another tutorial, but if you don’t plan on doing other tutorials, use the Confluent Cloud Console or CLI to destroy all of the resources you created. Verify they are destroyed to avoid unexpected charges.
Test it
Create a test configuration file
1
First, create a test file at configuration/test.properties: