首页 > 解决方案 > KStream 到 KTable 左连接返回 Null

问题描述

我目前正在尝试使用 KStream 到 KTable 连接来丰富 Kafka 主题。对于我的概念证明,我目前有一个 Kafka 流,其中包含大约 600,000 条记录,它们都具有相同的键,并且从一个主题创建的 KTable 具有 1 条记录的键、值对,其中 KTable 主题中的键与 600,000 的键匹配创建 KStream 的主题中的记录。

当我使用左连接(通过下面的代码)时,所有记录在 ValueJoiner 上都返回 NULL。

Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-pipe-json-parse-" + System.currentTimeMillis());
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "xxx.xx.xx.xxx:9092");        
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());   
props.put(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, "org.apache.kafka.streams.processor.WallclockTimestampExtractor");
props.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 5);


final StreamsBuilder builder = new StreamsBuilder();
// Build a Kafka Stream from the Netcool Input Topic
KStream<String, String> source = builder.stream("output-100k");


// Join the KStream to the KTable
KStream<String, String> enriched_output = source
    .leftJoin(netcool_enrichment, (orig_msg, description) -> {
        String new_msg = jsonEnricher(orig_msg, description);
        if (description != null) {
            System.out.println("\n[DEBUG] Enriched Input Orig: " + orig_msg);
            System.out.println("[DEBUG] Enriched Input Desc: " + description);                
            System.out.println("[DEBUG] Enriched Output: " + new_msg);
        }
        return new_msg;
        });

这是来自源 KStream 的示例输出记录(使用 forEach 循环):

[KSTREAM] Key: ismlogs
[KSTREAM] Value: {"severity":"debug","ingested_timestamp":"2018-07-18T19:32:47.227Z","@timestamp":"2018-06-28T23:36:31.000Z","offset":482,"@metadata":{"beat":"filebeat","topic":"input-100k","type":"doc","version":"6.2.2"},"beat":{"hostname":"abc.dec.com","name":"abc.dec.com","version":"6.2.2"},"source":"/root/100k-raw.txt","message":"Thu Jun 28 23:36:31 2018 Debug: Checking status of file /ism/profiles/active/test.xml","key":"ismlogs","tags":["ismlogs"]}

我尝试将 KTable 转换回 KStream 并在转换后的 Stream 上使用 forEach 循环,并验证记录实际上存在于 KTable 中。

KTable<String, String> enrichment = builder.table("enrichment");
KStream<String, String> ktable_debug = enrichment.toStream();
ktable_debug.foreach(new ForeachAction<String, String>() {
    public void apply(String key, String value) {
        System.out.println("[KTABLE] Key: " + key);
        System.out.println("[KTABLE] Value: " + value);
    }
 });

上面的代码输出:

[KTABLE] Key: "ismlogs"
[KTABLE] Value: "ISM Logs"

标签: javaapache-kafkaapache-kafka-streamskafka-join

解决方案


根据您的控制台消息,密钥不同,因此它们不会加入:

[KSTREAM] Key: ismlogs
[KTABLE] Key: "ismlogs"

在 的情况下KTable,关键实际上"ismlogs"是双引号。


推荐阅读