将多个行文本作为 kafka 主题中的一条消息推送

Sca*_*bie 6 apache-kafka kafka-producer-api

我想将包含多行的文本作为一条消息推送到 kafka 主题中。

我输入后:

kafka-console-producer --broker-list localhost:9092 --topic myTopic
Run Code Online (Sandbox Code Playgroud)

并复制我的文字:

My Text consists of:
two lines instead of one
Run Code Online (Sandbox Code Playgroud)

我在 kafka 主题中收到两条消息,但我只想拥有一条。任何想法如何实现这一目标?谢谢

Rob*_*att 8

kafkacat为此,您可以使用它的-D运算符来指定自定义消息分隔符(在本例中/):

kafkacat -b kafka:29092 \
        -t test_topic_01 \
        -D/ \
        -P <<EOF
this is a string message 
with a line break/this is 
another message with two 
line breaks!
EOF
Run Code Online (Sandbox Code Playgroud)

请注意,分隔符必须是单字节 - 多字节字符最终将包含在结果消息中请参阅问题 #140

结果消息,也使用 kafkacat 检查:

$ kafkacat -b kafka:29092 -C \
         -f '\nKey (%K bytes): %k\t\nValue (%S bytes): %s\n\Partition: %p\tOffset: %o\n--\n' \
         -t test_topic_01

Key (-1 bytes):
Value (43 bytes): this is a string message
with a line break
Partition: 0    Offset: 0
--

Key (-1 bytes):
Value (48 bytes): this is
another message with two
line breaks!

Partition: 0    Offset: 1
--
% Reached end of topic test_topic_01 [0] at offset 2
Run Code Online (Sandbox Code Playgroud)

检查使用kafka-console-consumer

$ kafka-console-consumer \
    --bootstrap-server kafka:29092 \
    --topic test_topic_01 \
    --from-beginning

this is a string message
with a line break
this is
another message with two
line breaks!
Run Code Online (Sandbox Code Playgroud)

因此说明了为什么kafkacat使用它比kafka-console-consumer因为它的可选冗长性更好:)


cri*_*007 5

这是不可能的,kafka-console-producer因为它使用以换行符分隔的 Java Scanner 对象。

您需要通过自己的生产者代码来完成