import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
public class WindowStreamDemo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put(StreamsConfig.APPLICATION_ID_CONFIG,"windowdemo");
properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.159.100:9092");
properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG,Serdes.String().getClass());
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
properties.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG,3000);
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,false);
StreamsBuilder builder = new StreamsBuilder();
SessionWindowedKStream<String, String> windowsdemo = builder.stream("windowsdemo")
.flatMapValues((value) -> {
String[] split = value.toString().split("\\s");
return Arrays.asList(split);
}).map((key, value) -> {
return new KeyValue<String, String>(value, "1");
}).groupByKey()
.windowedBy(SessionWindows.with(Duration.ofSeconds(15).toMillis()));
KStream<Windowed<String>, Long> wlks = windowsdemo.count().toStream();
wlks.foreach((key,value)->{
System.out.println(key+"-->"+value);
});
Topology topo = builder.build();
KafkaStreams kafkaStreams = new KafkaStreams(topo, properties);
CountDownLatch latch = new CountDownLatch(1);
Runtime.getRuntime().addShutdownHook(new Thread("线程1"){
@Override
public void run() {
kafkaStreams.close();
latch.countDown();
}
});
kafkaStreams.start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(0);
}
}