kamaci
kamaci

Reputation: 75137

Aggregate Stream Data with Kafka Streams

I am producing messages to Kafka with a code like that:

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "testo");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

Producer<String, String> producer = new KafkaProducer<>(props);

for (int i = 0; i < 1000; i++) {
  producer.send(new ProducerRecord<>(
    "topico",
    String.format("{\"type\":\"test\", \"t\":%.3f, \"k\":%d}", System.nanoTime() * 1e-9, i)));
}

I want to count to total messages within last hour with Kafka Streams (0.10.0.1). I've tried that:

final KStreamBuilder builder = new KStreamBuilder();
final KStream<String, String> metrics = builder.stream(Serdes.String(), Serdes.String(), "topico");
metrics.countByKey(TimeWindows.of("Hourly", 3600 * 1000)).mapValues(Object::toString).to("output");

I am so new to Kafka/Streams. How can I do it?

Upvotes: 1

Views: 1553

Answers (3)

Nonika
Nonika

Reputation: 2560

I'm also new with kafka streams, I don't know the old api but with new one (2.1.x) something like this should work

 kstream.mapValues((readOnlyKey, value) -> "test")
                    .groupByKey()
                    .windowedBy(TimeWindows.of(1000 * 60))
                    .count()
                    .toStream()
                    .selectKey((key, value) -> Instant.ofEpochMilli(key.window().end())
                            .truncatedTo(ChronoUnit.HOURS).toEpochMilli())
                    .groupByKey(Serialized.with(Serdes.Long(), Serdes.Long())).reduce((reduce, newVal) -> reduce + newVal)
                    .toStream().peek((key, value) -> log.info("{}={}",key,value));

Upvotes: 1

Santosh Rachakonda
Santosh Rachakonda

Reputation: 143

To aggregate two streams you can make use of the join method. There are different joins available in kstreams.

For example: if you want to join kstream with ktable:

KStream<String, String> left = builder.stream("topic1");
KTable<String, String> right = builder.table("topic2");

left.leftjoin((right, (leftValue, rightValue) -> Customfunction(rightValue, leftValue))

finally start the kstream

streams = new KafkaStreams(topology, config);
streams.start();

Upvotes: 1

Gilles Essoki
Gilles Essoki

Reputation: 557

First of all .. You lack this code to actually start your streaming process..

KafkaStreams streams = new KafkaStreams(builder, config);   
streams.start();    
Runtime.getRuntime().addShutdownHook(new Thread(streams::close)); 

Upvotes: 2

Related Questions