How can you dynamically route records to different Kafka topics, like a "topic exchange"?
Use the TopicNameExtractor
interface to apply runtime logic to choose the output topic.
The example below derives the output topic name from the record’s value, but it can also be derived from the record’s header (i.e., recordContext
) or key.
final TopicNameExtractor <String, CompletedOrder> orderTopicNameExtractor = (key, completedOrder, recordContext) -> {
final String compositeId = completedOrder.getId();
final String skuPart = compositeId.substring(compositeId.indexOf('-') + 1, 5);
final String outTopic;
if (skuPart.equals("QUA")) {
outTopic = specialOrderOutput;
} else {
outTopic = orderOutputTopic;
}
return outTopic;
};
This tutorial installs Confluent Platform using Docker. Before proceeding:
• Install Docker Desktop (version 4.0.0
or later) or Docker Engine (version 19.03.0
or later) if you don’t already have it
• Install the Docker Compose plugin if you don’t already have it. This isn’t necessary if you have Docker Desktop since it includes Docker Compose.
• Start Docker if it’s not already running, either by starting Docker Desktop or, if you manage Docker Engine with systemd
, via systemctl
• Verify that Docker is set up properly by ensuring no errors are output when you run docker info
and docker compose version
on the command line
To get started, make a new directory anywhere you’d like for this project:
mkdir dynamic-output-topic && cd dynamic-output-topic
Next, create the following docker-compose.yml
file to obtain Confluent Platform (for Kafka in the cloud, see Confluent Cloud):
version: '2'
services:
broker:
image: confluentinc/cp-kafka:7.4.1
hostname: broker
container_name: broker
ports:
- 29092:29092
environment:
KAFKA_BROKER_ID: 1
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_NODE_ID: 1
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093
KAFKA_LISTENERS: PLAINTEXT://broker:9092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:29092
KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LOG_DIRS: /tmp/kraft-combined-logs
CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk
schema-registry:
image: confluentinc/cp-schema-registry:7.3.0
hostname: schema-registry
container_name: schema-registry
depends_on:
- broker
ports:
- 8081:8081
environment:
SCHEMA_REGISTRY_HOST_NAME: schema-registry
SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: broker:9092
SCHEMA_REGISTRY_LOG4J_ROOT_LOGLEVEL: WARN
And launch it by running:
docker compose up -d
Create the following Gradle build file, named build.gradle
for the project:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "gradle.plugin.com.github.jengelman.gradle.plugins:shadow:7.0.0"
}
}
plugins {
id "java"
id "idea"
id "eclipse"
id "com.github.davidmc24.gradle.plugin.avro" version "1.7.0"
}
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
version = "0.0.1"
repositories {
mavenCentral()
maven {
url "https://packages.confluent.io/maven"
}
}
apply plugin: "com.github.johnrengelman.shadow"
dependencies {
implementation "org.apache.avro:avro:1.11.1"
implementation "org.slf4j:slf4j-simple:2.0.7"
implementation 'org.apache.kafka:kafka-streams:3.4.0'
implementation ('org.apache.kafka:kafka-clients') {
version {
strictly '3.4.0'
}
}
implementation "io.confluent:kafka-streams-avro-serde:7.3.0"
testImplementation "org.apache.kafka:kafka-streams-test-utils:3.4.0"
testImplementation "junit:junit:4.13.2"
testImplementation 'org.hamcrest:hamcrest:2.2'
}
test {
testLogging {
outputs.upToDateWhen { false }
showStandardStreams = true
exceptionFormat = "full"
}
}
jar {
manifest {
attributes(
"Class-Path": configurations.compileClasspath.collect { it.getName() }.join(" "),
"Main-Class": "io.confluent.developer.DynamicOutputTopic"
)
}
}
shadowJar {
archivesBaseName = "dynamic-output-topic-standalone"
archiveClassifier = ''
}
And be sure to run the following command to obtain the Gradle wrapper:
gradle wrapper
Next, create a directory for configuration data:
mkdir configuration
Then create a development file at configuration/dev.properties
:
application.id=dynamic-output-topic
bootstrap.servers=localhost:29092
schema.registry.url=http://localhost:8081
input.topic.name=input
input.topic.partitions=1
input.topic.replication.factor=1
output.topic.name=regular-order
output.topic.partitions=1
output.topic.replication.factor=1
special.order.topic.name=special-order
special.order.topic.partitions=1
special.order.topic.replication.factor=1
Create a directory for the schemas that represent the events in the stream:
mkdir -p src/main/avro
First create the following Avro schema file at src/main/avro/order.avsc
to create Order
objects to stream:
{
"namespace": "io.confluent.developer.avro",
"type": "record",
"name": "Order",
"fields": [
{"name": "id", "type": "long"},
{"name": "sku", "type": "string"},
{"name": "name", "type": "string"},
{"name": "quantity", "type": "long"}
]
}
Then create this Avro schema file at src/main/avro/completed-order.avsc
to create CompletedOrder
objects:
{
"namespace": "io.confluent.developer.avro",
"type": "record",
"name": "CompletedOrder",
"fields": [
{"name": "id", "type": "string"},
{"name": "name", "type": "string"},
{"name": "amount", "type": "double"}
]
}
Because we will use an Avro schema in our Java code, we’ll need to compile it. The Gradle Avro plugin is a part of the build, so it will see your new Avro files, generate Java code for them, and compile those and all other Java sources. Run this command to get it all done:
./gradlew build
Create a directory for the Java files in this project:
mkdir -p src/main/java/io/confluent/developer
The focus of this tutorial is using attributes in the output records to determine the correct output topic. For sending fully-processed records, typically you would use the KStream.to()
method, which takes the name of the output topic. You can think of this as setting the output topic statically.
For dynamic output topic choice, Kafka Streams has an overloaded version of the KStream.to()
method that takes a TopicNameExtractor
interface instead of a singular topic name. The TopicNameExtractor
interface contains only one method, extract
. This means you can use a lambda in most cases, instead of a concrete class.
The TopicNameExtractor.extract()
method accepts three parameters: the key, value, and RecordContext
of the current record. It returns a String
– the output topic to use.
Now take a detailed look at the TopicNameExtractor
you’ll use in this tutorial (found on line 67 in DynamicOutputTopic.java
)
final TopicNameExtractor <String, CompletedOrder> orderTopicNameExtractor = (key, completedOrder, recordContext) -> {
final String compositeId = completedOrder.getId();
final String skuPart = compositeId.substring(compositeId.indexOf('-') + 1, 5);
final String outTopic;
if (skuPart.equals("QUA")) {
outTopic = specialOrderOutput;
} else {
outTopic = orderOutputTopic;
}
return outTopic;
};
In the code above, the TopicNameExtractor
takes the CompletedOrder.id
field. Based on the extracted substring, it returns the name of the topic to use. You should also note that the topics need to be created ahead of time as with any of the topics used by Kafka Streams.
Now go ahead and create the following file at src/main/java/io/confluent/developer/DynamicOutputTopic.java
.
package io.confluent.developer;
import org.apache.avro.specific.SpecificRecord;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.apache.kafka.streams.processor.TopicNameExtractor;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import io.confluent.common.utils.TestUtils;
import io.confluent.developer.avro.CompletedOrder;
import io.confluent.developer.avro.Order;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
public class DynamicOutputTopic {
static final double FAKE_PRICE = 0.467423D;
public Topology buildTopology(Properties allProps) {
final StreamsBuilder builder = new StreamsBuilder();
final String orderInputTopic = allProps.getProperty("input.topic.name");
final String orderOutputTopic = allProps.getProperty("output.topic.name");
final String specialOrderOutput = allProps.getProperty("special.order.topic.name");
final Serde<String> stringSerde = Serdes.String();
final Serde<Order> orderSerde = getSpecificAvroSerde(allProps);
final Serde<CompletedOrder> completedOrderSerde = getSpecificAvroSerde(allProps);
final ValueMapper<Order, CompletedOrder> orderProcessingSimulator = v -> {
double amount = v.getQuantity() * FAKE_PRICE;
return CompletedOrder.newBuilder().setAmount(amount).setId(v.getId() + "-" + v.getSku()).setName(v.getName()).build();
};
final TopicNameExtractor<String, CompletedOrder> orderTopicNameExtractor = (key, completedOrder, recordContext) -> {
final String compositeId = completedOrder.getId();
final String skuPart = compositeId.substring(compositeId.indexOf('-') + 1, 5);
final String outTopic;
if (skuPart.equals("QUA")) {
outTopic = specialOrderOutput;
} else {
outTopic = orderOutputTopic;
}
return outTopic;
};
final KStream<String, Order> exampleStream = builder.stream(orderInputTopic, Consumed.with(stringSerde, orderSerde));
exampleStream.mapValues(orderProcessingSimulator).to(orderTopicNameExtractor, Produced.with(stringSerde, completedOrderSerde));
return builder.build();
}
static <T extends SpecificRecord> SpecificAvroSerde<T> getSpecificAvroSerde(final Properties allProps) {
final SpecificAvroSerde<T> specificAvroSerde = new SpecificAvroSerde<>();
final Map<String, String> serdeConfig = (Map)allProps;
specificAvroSerde.configure(serdeConfig, false);
return specificAvroSerde;
}
public void createTopics(final Properties allProps) {
try (final AdminClient client = AdminClient.create(allProps)) {
final List<NewTopic> topics = new ArrayList<>();
topics.add(new NewTopic(
allProps.getProperty("input.topic.name"),
Integer.parseInt(allProps.getProperty("input.topic.partitions")),
Short.parseShort(allProps.getProperty("input.topic.replication.factor"))));
topics.add(new NewTopic(
allProps.getProperty("output.topic.name"),
Integer.parseInt(allProps.getProperty("output.topic.partitions")),
Short.parseShort(allProps.getProperty("output.topic.replication.factor"))));
topics.add(new NewTopic(
allProps.getProperty("special.order.topic.name"),
Integer.parseInt(allProps.getProperty("special.order.topic.partitions")),
Short.parseShort(allProps.getProperty("special.order.topic.replication.factor"))));
client.createTopics(topics);
}
}
public Properties loadEnvProperties(String fileName) throws IOException {
final Properties allProps = new Properties();
final FileInputStream input = new FileInputStream(fileName);
allProps.load(input);
input.close();
return allProps;
}
public static void main(String[] args) throws Exception {
if (args.length < 1) {
throw new IllegalArgumentException("This program takes one argument: the path to an environment configuration file.");
}
final DynamicOutputTopic instance = new DynamicOutputTopic();
final Properties allProps = new Properties();
try (InputStream inputStream = new FileInputStream(args[0])) {
allProps.load(inputStream);
}
allProps.put(StreamsConfig.APPLICATION_ID_CONFIG, allProps.getProperty("application.id"));
allProps.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath());
final Topology topology = instance.buildTopology(allProps);
instance.createTopics(allProps);
final KafkaStreams streams = new KafkaStreams(topology, allProps);
final CountDownLatch latch = new CountDownLatch(1);
// Attach shutdown handler to catch Control-C.
Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
@Override
public void run() {
streams.close(Duration.ofSeconds(5));
latch.countDown();
}
});
try {
streams.start();
latch.await();
} catch (Throwable e) {
System.exit(1);
}
System.exit(0);
}
}
In your terminal, run:
./gradlew shadowJar
Now that you have an uberjar for the Kafka Streams application, you can launch it locally. When you run the following, the prompt won’t return, because the application will run until you exit it. There is always another message to process, so streaming applications don’t exit until you force them.
java -jar build/libs/dynamic-output-topic-standalone-0.0.1.jar configuration/dev.properties
In a new terminal, run:
docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic input --bootstrap-server broker:9092 \
--property "parse.key=true" \
--property 'key.schema={"type":"string"}' \
--property "key.separator=:" \
--property value.schema="$(< src/main/avro/order.avsc)"
When the console producer starts, it will log some messages and hang, waiting for your input. Each line represents input data for the Kafka Streams application. To send all of the events below, paste the following into the prompt and press enter:
"5":{"id":5,"name":"tp","quantity":10000, "sku":"QUA00000123"}
"6":{"id":6,"name":"coffee","quantity":1000, "sku":"COF0003456"}
"7":{"id":7,"name":"hand-sanitizer","quantity":6000, "sku":"QUA000022334"}
"8":{"id":8,"name":"beer","quantity":4000, "sku":"BER88899222"}
Now that you have produced some orders, you should set up a consumer to view the results. In this case, you need to start two consumers as the Kafka Streams
application dynamically chooses which output topic to use depending on information contained in the Order
object.
In a new terminal window start the following console consumer to view regular sized Order
objects.
docker exec -it schema-registry /usr/bin/kafka-avro-console-consumer --topic regular-order --bootstrap-server broker:9092 --from-beginning
You should see output that looks like this:
{"id":"6-COF0003456","name":"coffee","amount":467.423}
{"id":"8-BER88899222","name":"beer","amount":1869.692}
Then close the current console consumer or open a second terminal window and start another console consumer to view the special CompletedOrder
objects. Remember the Kafka Streams application determines at runtime where to send each order based on the information contained in the CompletedOrder
object.
docker exec -it schema-registry /usr/bin/kafka-avro-console-consumer --topic special-order --bootstrap-server broker:9092 --from-beginning
The special order console consumer should yield this output:
{"id":"5-QUA00000123","name":"tp","amount":4674.23}
{"id":"7-QUA000022334","name":"hand-sanitizer","amount":2804.538}
First, create a test file at configuration/test.properties
:
application.id=dynamic-output-topic
bootstrap.servers=localhost:29092
schema.registry.url=mock://dynamic-output-topic-test
input.topic.name=input
input.topic.partitions=1
input.topic.replication.factor=1
output.topic.name=regular-order
output.topic.partitions=1
output.topic.replication.factor=1
special.order.topic.name=special-order
special.order.topic.partitions=1
special.order.topic.replication.factor=1
Create a directory for the tests to live in:
mkdir -p src/test/java/io/confluent/developer
Now create the following file at src/test/java/io/confluent/developer/DynamicOutputTopicTest.java
. Testing a Kafka streams application requires a bit of test harness code, but happily the org.apache.kafka.streams.TopologyTestDriver
class makes this much more pleasant that it would otherwise be.
There is only one method in DynamicOutputTopicTest
annotated with @Test
, and that is shouldChooseCorrectOutputTopic()
. This method actually runs our Streams topology using the TopologyTestDriver
and some mocked data that is set up inside the test method.
package io.confluent.developer;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import io.confluent.developer.avro.CompletedOrder;
import io.confluent.developer.avro.Order;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class DynamicOutputTopicTest {
private final static String TEST_CONFIG_FILE = "configuration/test.properties";
@Test
public void shouldChooseCorrectOutputTopic() throws IOException {
final DynamicOutputTopic instance = new DynamicOutputTopic();
final Properties allProps = new Properties();
try (InputStream inputStream = new FileInputStream(TEST_CONFIG_FILE)) {
allProps.load(inputStream);
}
final String orderInputTopic = allProps.getProperty("input.topic.name");
final String orderOutputTopic = allProps.getProperty("output.topic.name");
final String specialOrderOutputTopic = allProps.getProperty("special.order.topic.name");
final Topology topology = instance.buildTopology(allProps);
try (final TopologyTestDriver testDriver = new TopologyTestDriver(topology, allProps)) {
final Serde<String> stringSerde = Serdes.String();
final SpecificAvroSerde<Order> orderAvroSerde = DynamicOutputTopic.getSpecificAvroSerde(allProps);
final SpecificAvroSerde<CompletedOrder>
completedOrderAvroSerde =
DynamicOutputTopic.getSpecificAvroSerde(allProps);
final Serializer<String> keySerializer = stringSerde.serializer();
final Deserializer<String> keyDeserializer = stringSerde.deserializer();
final Serializer<Order> orderSerializer = orderAvroSerde.serializer();
final Deserializer<CompletedOrder> completedOrderDeserializer = completedOrderAvroSerde.deserializer();
final TestInputTopic<String, Order>
inputTopic =
testDriver.createInputTopic(orderInputTopic, keySerializer, orderSerializer);
final TestOutputTopic<String, CompletedOrder>
orderTopic =
testDriver.createOutputTopic(orderOutputTopic, keyDeserializer, completedOrderDeserializer);
final TestOutputTopic<String, CompletedOrder>
specialOrderTopic =
testDriver.createOutputTopic(specialOrderOutputTopic, keyDeserializer, completedOrderDeserializer);
final List<Order> orders = new ArrayList<>();
orders.add(Order.newBuilder().setId(5L).setName("tp").setQuantity(10_000L).setSku("QUA00000123").build());
orders.add(Order.newBuilder().setId(6L).setName("coffee").setQuantity(1_000L).setSku("COF0003456").build());
orders.add(
Order.newBuilder().setId(7L).setName("hand-sanitizer").setQuantity(6_000L).setSku("QUA000022334").build());
orders.add(Order.newBuilder().setId(8L).setName("beer").setQuantity(4_000L).setSku("BER88899222").build());
final List<CompletedOrder> expectedRegularCompletedOrders = new ArrayList<>();
expectedRegularCompletedOrders.add(CompletedOrder.newBuilder().setName("coffee").setId("6-COF0003456")
.setAmount(1_000L * DynamicOutputTopic.FAKE_PRICE).build());
expectedRegularCompletedOrders.add(CompletedOrder.newBuilder().setName("beer").setId("8-BER88899222")
.setAmount(4_000L * DynamicOutputTopic.FAKE_PRICE).build());
final List<CompletedOrder> expectedSpecialOrders = new ArrayList<>();
expectedSpecialOrders.add(CompletedOrder.newBuilder().setId("5-QUA00000123").setName("tp")
.setAmount(10_000L * DynamicOutputTopic.FAKE_PRICE).build());
expectedSpecialOrders.add(CompletedOrder.newBuilder().setId("7-QUA000022334").setName("hand-sanitizer")
.setAmount(6_000L * DynamicOutputTopic.FAKE_PRICE).build());
for (final Order order : orders) {
inputTopic.pipeInput(String.valueOf(order.getId()), order);
}
final List<CompletedOrder> actualRegularOrderResults = orderTopic.readValuesToList();
final List<CompletedOrder> actualSpecialCompletedOrders = specialOrderTopic.readValuesToList();
assertThat(expectedRegularCompletedOrders, equalTo(actualRegularOrderResults));
assertThat(expectedSpecialOrders, equalTo(actualSpecialCompletedOrders));
}
}
}
Now run the test, which is as simple as:
./gradlew test
Instead of running a local Kafka cluster, you may use Confluent Cloud, a fully managed Apache Kafka service.
Sign up for Confluent Cloud, a fully managed Apache Kafka service.
After you log in to Confluent Cloud Console, 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.
Next, from the Confluent Cloud Console, click on Clients
to get the cluster-specific configurations, e.g., Kafka cluster bootstrap servers and credentials, Confluent Cloud Schema Registry and credentials, etc., and set the appropriate parameters in your client application.
In the case of this tutorial, add the following properties to the client application’s input properties file, substituting all curly braces with your Confluent Cloud values.
# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BROKER_ENDPOINT }}
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=https://{{ SR_ENDPOINT }}
basic.auth.credentials.source=USER_INFO
schema.registry.basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}
Now you’re all set to run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.