props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, TemperatureReadingTimestampExtractor.class.getName());
How can you create windowed calculations on time series data with small advances in time?
To use SlidingWindows
use the SlidingWindows.withTimeDifferenceAndGrace
method inside a windowedBy
call.
builder.stream(<INPUT TOPIC>, Consumed.with(<KEY SERDE>, <VALUE SERDE>))
.groupByKey()
.windowedBy(SlidingWindows.withTimeDifferenceAndGrace(Duration.ofSeconds(1), Duration.ofSeconds(1)))
.<Aggregation Operation>....
The first parameter determines the maximum time difference between records in the same window, and the second parameter sets the grace period for allowing out-of-order events into the window. For specifics on sliding windows you can read KIP-450.
You can get similar behavior in hopping windows by defining a short advance time. But this will result in poor performance because hopping windows will create many overlapping, possibly redundant windows. Performing aggregation operations over redundant windows costs CPU time, which can be expensive. Sliding windows only create windows containing distinct items, and perform calculations on these is more efficient. Additionally, sliding windows are inclusive on both the start and end time vs. hopping windows being inclusive only on the start time.
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 sliding-windows && cd sliding-windows
Create a Dockerfile called Dockerfile-connect
that builds a custom container for Kafka Connect bundled with the free and open source Kafka Connect Datagen connector, installed from Confluent Hub.
FROM confluentinc/cp-kafka-connect-base:7.3.0
ENV CONNECT_PLUGIN_PATH="/usr/share/java,/usr/share/confluent-hub-components"
RUN confluent-hub install --no-prompt confluentinc/kafka-connect-datagen:0.6.0
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
connect:
image: localimage/kafka-connect-datagen:latest
build:
context: .
dockerfile: Dockerfile-connect
container_name: connect
depends_on:
- broker
- schema-registry
ports:
- 8083:8083
volumes:
- ./datagen-temperature-reading.avsc:/tmp/datagen-temperature-reading.avsc
environment:
CONNECT_BOOTSTRAP_SERVERS: broker:9092
CONNECT_REST_ADVERTISED_HOST_NAME: connect
CONNECT_GROUP_ID: kafka-connect
CONNECT_CONFIG_STORAGE_TOPIC: _kafka-connect-configs
CONNECT_OFFSET_STORAGE_TOPIC: _kafka-connect-offsets
CONNECT_STATUS_STORAGE_TOPIC: _kafka-connect-status
CONNECT_KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
CONNECT_VALUE_CONVERTER: io.confluent.connect.avro.AvroConverter
CONNECT_VALUE_CONVERTER_SCHEMA_REGISTRY_URL: http://schema-registry:8081
CONNECT_LOG4J_ROOT_LOGLEVEL: INFO
CONNECT_LOG4J_LOGGERS: org.apache.kafka.connect.runtime.rest=WARN,org.reflections=ERROR
CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: '1'
CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: '1'
CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: '1'
Now launch Confluent Platform by running the following command. Note the --build
argument which automatically builds the Docker image for Kafka Connect and the bundled kafka-connect-datagen connector.
docker compose up -d --build
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.SlidingWindow"
)
}
}
shadowJar {
archiveBaseName = "sliding-windows-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=sliding-windows
bootstrap.servers=localhost:29092
schema.registry.url=http://localhost:8081
input.topic.name=temp-readings
input.topic.partitions=1
input.topic.replication.factor=1
output.topic.name=output-topic
output.topic.partitions=1
output.topic.replication.factor=1
Create a directory for the schemas that represent the events in the stream:
mkdir -p src/main/avro
Then create the following Avro schema file at src/main/avro/temperature_reading.avsc
for our TemperatureReading
object:
{
"namespace": "io.confluent.developer.avro",
"type": "record",
"name": "TemperatureReading",
"fields": [
{ "name": "temp", "type": "double" },
{ "name": "timestamp", "type": "long" } ,
{ "name": "device_id", "type": "string" }
]
}
You’ll also need to create another schema src/main/avro/temp_average.avsc
for the TempAverage
object that Kafka Streams will use for holding the data needed to perform the aggregation.
{
"namespace": "io.confluent.developer.avro",
"type": "record",
"name": "TempAverage",
"fields": [
{
"name": "total",
"type": "double"
},
{
"name": "num_readings",
"type": "long"
}
]
}
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
First, create a directory for the Java files in this project:
mkdir -p src/main/java/io/confluent/developer
Before you create the Kafka Streams application you’ll need to create an instance of a TimestampExtractor. In Kafka Streams, timestamps drive the progress of records in the application. By default, Kafka Streams uses the timestamps contained in the ConsumerRecord. But you can configure your application to use timestamps embedded in the record payload itself. You do this by creating an class implementing the TimestampExtractor
interface and provide the class name when configuring your Kafka Streams application like so:
props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, TemperatureReadingTimestampExtractor.class.getName());
We’re going to create a custom TimestampExtractor
so the Kafka Streams application uses the timestamps embedded in our generated IoT sensor readings.
Create the following file at src/main/java/io/confluent/developer/TemperatureReadingTimestampExtractor.java
package io.confluent.developer;
import io.confluent.developer.avro.TemperatureReading;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.streams.processor.TimestampExtractor;
public class TemperatureReadingTimestampExtractor implements TimestampExtractor {
@Override
public long extract(ConsumerRecord<Object, Object> record, long previousTimestamp) {
return ((TemperatureReading)record.value()).getTimestamp();
}
}
You’ll take care of the configuration when you create the Kafka Streams topology in the next step.
Before you create the Kafka Streams application let’s go over the key points. In this tutorial you’ll learn about using SlidingWindows for aggregation operations. Incoming record timestamps drive the window behavior, and the time difference between records plus a grace period for out-of-order records (both are user defined) drives the size of the window.
builder.stream(tempReadingTopic, Consumed.with(Serdes.String(), temReadingSerde))
.groupByKey() (1)
.windowedBy(SlidingWindows.withTimeDifferenceAndGrace(Duration.ofSeconds(1), Duration.ofSeconds(1))) (2)
.aggregate(TempAverage::new, (k, tr, ave) -> { (3)
ave.setNumReadings(ave.getNumReadings() +1);
ave.setTotal(ave.getTotal() + tr.getTemp());
return ave;
}, Materialized.with(Serdes.String(), tempAveSerde))
1 | Grouping by key, a prerequisite for aggregation operations |
2 | Specifying a sliding window for the windowing operation |
3 | The aggregation operation which sums the temperature and keeps a total count of the readings |
As the window "slides" over the record stream, a new window is created each time a record enters or exits the window. Records that arrive after grace period are dropped. A window closes when stream-time
exceeds the window-end
+ grace-period
You can get similar behavior in hopping windows by defining a short advance time. But this will result in poor performance because hopping windows will create many overlapping, possibly redundant windows. Performing aggregation operations over redundant windows costs CPU time, which can be expensive. Sliding windows only create windows containing distinct items, and perform calculations on these is more efficient. Additionally, sliding windows are inclusive on both the start and end time vs. hopping windows being inclusive only on the start time.
The concept of stream-time is the largest timestamp processed by Kafka Streams at a given point in time. A grace-period is the amount of time you’re allowing out-of-order records to be included in a window.
|
That wraps up our discussion for the finer points of the code for this tutorial. Now create the following file at src/main/java/io/confluent/developer/SlidingWindow.java
package io.confluent.developer;
import io.confluent.developer.avro.TempAverage;
import io.confluent.developer.avro.TemperatureReading;
import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
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.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
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.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.SlidingWindows;
import org.apache.kafka.streams.kstream.Windowed;
import java.io.FileInputStream;
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 static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
public class SlidingWindow {
public Properties buildStreamsProperties(Properties envProps) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, envProps.getProperty("application.id"));
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, envProps.getProperty("bootstrap.servers"));
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
props.put(SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));
props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, TemperatureReadingTimestampExtractor.class.getName());
// Setting this to a low value on purpose to flush the cache quickly during the demo
// Normally you'll want to keep this setting at the default value of 30 seconds
props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 1000);
return props;
}
public Topology buildTopology(Properties envProps) {
final StreamsBuilder builder = new StreamsBuilder();
final String tempReadingTopic = envProps.getProperty("input.topic.name");
final String aveTempOutputTopic = envProps.getProperty("output.topic.name");
final SpecificAvroSerde<TemperatureReading> temReadingSerde = getSpecificAvroSerde(envProps);
final SpecificAvroSerde<TempAverage> tempAveSerde = getSpecificAvroSerde(envProps);
builder.stream(tempReadingTopic, Consumed.with(Serdes.String(), temReadingSerde))
.groupByKey()
.windowedBy(SlidingWindows.ofTimeDifferenceAndGrace(Duration.ofMillis(500), Duration.ofMillis(100)))
.aggregate(TempAverage::new, (k, tr, ave) -> {
ave.setNumReadings(ave.getNumReadings() +1);
ave.setTotal(ave.getTotal() + tr.getTemp());
return ave;
}, Materialized.with(Serdes.String(), tempAveSerde))
.toStream()
.map((Windowed<String> key, TempAverage tempAverage) -> {
double aveNoFormat = tempAverage.getTotal()/(double)tempAverage.getNumReadings();
double formattedAve = Double.parseDouble(String.format("%.2f", aveNoFormat));
return new KeyValue<>(key.key(),formattedAve) ;
})
.to(aveTempOutputTopic, Produced.with(Serdes.String(), Serdes.Double()));
return builder.build();
}
static <T extends SpecificRecord> SpecificAvroSerde<T> getSpecificAvroSerde(final Properties envProps) {
final SpecificAvroSerde<T> specificAvroSerde = new SpecificAvroSerde<>();
final HashMap<String, String> serdeConfig = new HashMap<>();
serdeConfig.put(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
envProps.getProperty("schema.registry.url"));
specificAvroSerde.configure(serdeConfig, false);
return specificAvroSerde;
}
public void createTopics(Properties envProps) {
Map<String, Object> config = new HashMap<>();
config.put("bootstrap.servers", envProps.getProperty("bootstrap.servers"));
try (AdminClient client = AdminClient.create(config)) {
List<NewTopic> topics = new ArrayList<>();
NewTopic ratings = new NewTopic(envProps.getProperty("input.topic.name"),
Integer.parseInt(envProps.getProperty("input.topic.partitions")),
Short.parseShort(envProps.getProperty("input.topic.replication.factor")));
topics.add(ratings);
NewTopic counts = new NewTopic(envProps.getProperty("output.topic.name"),
Integer.parseInt(envProps.getProperty("output.topic.partitions")),
Short.parseShort(envProps.getProperty("output.topic.replication.factor")));
topics.add(counts);
client.createTopics(topics);
}
}
public Properties loadEnvProperties(String fileName) throws IOException {
Properties envProps = new Properties();
FileInputStream input = new FileInputStream(fileName);
envProps.load(input);
input.close();
return envProps;
}
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.");
}
SlidingWindow tw = new SlidingWindow();
Properties envProps = tw.loadEnvProperties(args[0]);
Properties streamProps = tw.buildStreamsProperties(envProps);
Topology topology = tw.buildTopology(envProps);
tw.createTopics(envProps);
final KafkaStreams streams = new KafkaStreams(topology, streamProps);
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();
latch.countDown();
}
});
try {
streams.cleanUp();
streams.start();
latch.await();
} catch (Throwable e) {
System.exit(1);
}
System.exit(0);
}
}
Before you start your Kafka Streams application, we need to provide data for it. Fortunately this is as simple as using a HTTP PUT
request, as you’re going to use the DatagenConnector
.
Now create the following Avro schema file datagen-temperature-reading.avsc
in the current working directory (sliding-windows
) for the tutorial:
{
"namespace": "io.confluent.developer.avro",
"type": "record",
"name": "TemperatureReading",
"fields": [
{ "name": "temp", "type": {
"type": "double",
"arg.properties": {
"range": { "min": 70.00, "max": 99.91}
}
}
},
{ "name": "timestamp", "type": {
"type": "long",
"format_as_time" : "unix_long",
"arg.properties": {
"iteration": { "start": 1, "step": 100}
}
}},
{ "name": "device_id", "type": {
"type": "string",
"arg.properties": {
"options": ["device-1", "device-2"]
}
}
}
]
}
This schema file is pretty much idential to the one you created earlier.
The only difference is this schema contains instructions for data generation. The kafka-connect-datagen connector uses the Avro Random Generator to generate data.
Open an new terminal window and run this command to start the data generator:
curl -i -X PUT http://localhost:8083/connectors/datagen_local_01/config \
-H "Content-Type: application/json" \
-d '{
"connector.class": "io.confluent.kafka.connect.datagen.DatagenConnector",
"key.converter": "org.apache.kafka.connect.storage.StringConverter",
"kafka.topic": "temp-readings",
"schema.filename": "/tmp/datagen-temperature-reading.avsc",
"schema.keyfield": "device_id",
"max.interval": 300,
"iterations": 10000000,
"tasks.max": "1"
}'
You should see something like this on the console indicating the datagen connector sucessfuly started
HTTP/1.1 201 Created Date: Tue, 26 Jan 2021 21:40:33 GMT Location: http://localhost:8083/connectors/datagen_local_01 Content-Type: application/json Content-Length: 413 Server: Jetty(9.4.24.v20191120) {"name":"datagen_local_01","config":{"connector.class":"io.confluent.kafka.connect.datagen.DatagenConnector","key.converter":"org.apache.kafka.connect.storage.StringConverter","kafka.topic":"temp-readings","schema.filename":"/schemas/datagen-temperature-reading.avsc","schema.keyfield":"device_id","max.interval":"300","iterations":"10000000","tasks.max":"1","name":"datagen_local_01"},"tasks":[],"type":"source"}
Now that we have data generation working, let’s build your application by running:
./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/sliding-windows-standalone-0.0.1.jar configuration/dev.properties
Now that your Kafka Streams application is running, open a new terminal window, change directories (cd
) into the sliding-windows
directory and start a console-consumer to confirm the output:
docker exec -t broker kafka-console-consumer \
--bootstrap-server broker:9092 \
--topic output-topic \
--property print.key=true \
--value-deserializer "org.apache.kafka.common.serialization.DoubleDeserializer" \
--property key.separator=" : " \
--from-beginning \
--max-messages 10
Your results should look someting like this:
device-1 : 79.77
device-1 : 80.63
device-2 : 89.87
device-1 : 79.76
device-1 : 80.06
device-1 : 82.06
device-2 : 73.63
device-2 : 81.75
device-1 : 86.32
device-1 : 82.82
Go ahead and shut down your streams application now with a CNTR+C
command.
First, create a test file at configuration/test.properties
:
application.id=sliding-windows-test
bootstrap.servers=localhost:29092
schema.registry.url=mock://localhost:8081
input.topic.name=temp-readings
input.topic.partitions=1
input.topic.replication.factor=1
output.topic.name=output-topic
output.topic.partitions=1
output.topic.replication.factor=1
Create a directory for the tests to live in:
mkdir -p src/test/java/io/confluent/developer
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 SlidingWindowTest
annotated with @Test
, and that is slidingWindowTest()
. This method actually runs our Streams topology using the TopologyTestDriver
and some mocked data that is set up inside the test method.
This test is straightforward, but there is one section we should look into a little more
final String key = "device-1";
final List<TemperatureReading> temperatureReadings = new ArrayList<>();
Instant instant = Instant.now().truncatedTo(ChronoUnit.MINUTES);
temperatureReadings.add(TemperatureReading.newBuilder().setDeviceId(key).setTemp(80.0).setTimestamp(instant.getEpochSecond()).build()); (1)
temperatureReadings.add(TemperatureReading.newBuilder().setDeviceId(key).setTemp(90.0).setTimestamp(instant.plusMillis(200).getEpochSecond()).build());
temperatureReadings.add(TemperatureReading.newBuilder().setDeviceId(key).setTemp(95.0).setTimestamp(instant.plusMillis(400).getEpochSecond()).build());
temperatureReadings.add(TemperatureReading.newBuilder().setDeviceId(key).setTemp(100.0).setTimestamp(instant.plusMillis(500).getEpochSecond()).build());
List<KeyValue<String, TemperatureReading>> keyValues = temperatureReadings.stream().map(o -> KeyValue.pair(o.getDeviceId(),o)).collect(Collectors.toList()); (2)
inputTopic.pipeKeyValueList(keyValues);
1 | Creating the input records for the test |
2 | Mapping the list of test records to KeyValue pairs |
The TestInputTopic provides useful methods when testing your topology. Here you’re using the pipeKeyValueList
to provide the records to the steams application. Here you’re not specifying any timestamp activity as the streams application pulls the timestamps embedded in the TemperatureReading
objects you created above.
Now create the following file at src/test/java/io/confluent/developer/SlidingWindowTest.java
.
package io.confluent.developer;
import io.confluent.common.utils.TestUtils;
import io.confluent.developer.avro.TemperatureReading;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsConfig;
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.After;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.IOException;
import java.nio.file.Files;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
public class SlidingWindowTest {
private final static String TEST_CONFIG_FILE = "configuration/test.properties";
@Test
public void slidingWindowTest() throws IOException {
final SlidingWindow instance = new SlidingWindow();
final Properties envProps = instance.loadEnvProperties(TEST_CONFIG_FILE);
final Properties streamProps = instance.buildStreamsProperties(envProps);
final String temperatureReadingsInputTopic = envProps.getProperty("input.topic.name");
final String outputTopicName = envProps.getProperty("output.topic.name");
final Topology topology = instance.buildTopology(envProps);
try (final TopologyTestDriver testDriver = new TopologyTestDriver(topology, streamProps)) {
final SpecificAvroSerde<TemperatureReading> exampleAvroSerde = SlidingWindow.getSpecificAvroSerde(envProps);
final Serializer<String> keySerializer = Serdes.String().serializer();
final Serializer<TemperatureReading> exampleSerializer = exampleAvroSerde.serializer();
final Deserializer<Double> valueDeserializer = Serdes.Double().deserializer();
final Deserializer<String> keyDeserializer = Serdes.String().deserializer();
final TestInputTopic<String, TemperatureReading> inputTopic = testDriver.createInputTopic(temperatureReadingsInputTopic,
keySerializer,
exampleSerializer);
final TestOutputTopic<String, Double> outputTopic = testDriver.createOutputTopic(outputTopicName, keyDeserializer, valueDeserializer);
final String key = "device-1";
final List<TemperatureReading> temperatureReadings = new ArrayList<>();
Instant instant = Instant.now().truncatedTo(ChronoUnit.MINUTES);
temperatureReadings.add(TemperatureReading.newBuilder().setDeviceId(key).setTemp(80.0).setTimestamp(instant.getEpochSecond()).build());
temperatureReadings.add(TemperatureReading.newBuilder().setDeviceId(key).setTemp(90.0).setTimestamp(instant.plusMillis(200).getEpochSecond()).build());
temperatureReadings.add(TemperatureReading.newBuilder().setDeviceId(key).setTemp(95.0).setTimestamp(instant.plusMillis(400).getEpochSecond()).build());
temperatureReadings.add(TemperatureReading.newBuilder().setDeviceId(key).setTemp(100.0).setTimestamp(instant.plusMillis(500).getEpochSecond()).build());
List<KeyValue<String, TemperatureReading>> keyValues = temperatureReadings.stream().map(o -> KeyValue.pair(o.getDeviceId(),o)).collect(Collectors.toList());
inputTopic.pipeKeyValueList(keyValues);
final List<KeyValue<String, Double>> expectedValues = Arrays.asList(KeyValue.pair(key, 80.0), KeyValue.pair(key, 85.0), KeyValue.pair(key, 88.33), KeyValue.pair(key, 91.25));
final List<KeyValue<String, Double>> actualResults = outputTopic.readKeyValuesToList();
assertEquals(expectedValues, actualResults);
}
}
}
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.