简体   繁体   English

使用 apache Flink 读取键控 Kafka 记录?

[英]Read a keyed Kafka Record using apache Flink?

i'm using a value + record kafka producer using:我正在使用 value + record kafka 生产者使用:

bin/kafka-console-producer.sh --topic test3 --property "parse.key=true" --property "key.separator=:" --bootstrap-server localhost:9092

but im finding hard to understand how to read those kafka records using Flink kafka consumer KafkaSource .但我发现很难理解如何使用 Flink kafka consumer KafkaSource读取这些 kafka 记录。 I want to be able to do things like:我希望能够做这样的事情:

record.getValue(), record.getKey(), record.getTimestamp()...

this is my current code that only reads non keyed records from kafka这是我当前的代码,它只从 kafka 读取非键控记录

        KafkaSource<String> source = KafkaSource.<String>builder()
            .setBootstrapServers(ip)
            .setTopics("test3")
            .setGroupId("1")
            .setStartingOffsets(OffsetsInitializer.earliest())
            .setDeserializer(KafkaRecordDeserializationSchema.valueOnly(StringDeserializer.class))
            .build();

    DataStream<String> stream = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");
    stream.map((MapFunction<String, String>) value -> "Receiving from Kafka : " + value).print();

can i get an example of what im looking for?我能举个例子说明我在找什么吗?

You need to implement a KafkaRecordDeserializationSchema (but not valueOnly), and then in its deserialize method you'll have access to a ConsumerRecord, and you can work with its key, value, headers, etc to produce whatever type you want.您需要实施KafkaRecordDeserializationSchema (但不是 valueOnly),然后在其反序列化方法中您将有权访问 ConsumerRecord,并且您可以使用其键、值、标头等来生成您想要的任何类型。

There's an example in Reading Apache Kafka® headers , which is part of the Immerok Apache Flink Cookbook. Reading Apache Kafka® headers中有一个示例,它是 Immerok Apache Flink Cookbook 的一部分。 Note that while that example accesses the topic, partition, offset, and timestamp from the record's headers, it doesn't use the key, which is available as record.key() .请注意,虽然该示例从记录的标头访问主题、分区、偏移量和时间戳,但它不使用键,该键可用作record.key()

Note: I work for Immerok.注意:我为 Immerok 工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM