在 kafka 主题中将多行文本作为一条消息推送
push multiple Line Text as one message in a kafka topic
我想将包含多行的文本作为一条消息推送到 kafka 主题中。
我输入后:
kafka-console-producer --broker-list localhost:9092 --topic myTopic
并复制我的文字:
My Text consists of:
two lines instead of one
我在 kafka 主题中收到两条消息,但我只想收到一条消息。任何想法如何实现?谢谢
kafka-console-producer
不可能,因为它使用 Java 以换行符分隔的扫描仪对象。
您需要通过自己的生产者代码来完成
对于 Console-consumer,您显然是在 运行 测试来自客户端的预期数据。如果它是单个消息,最好通过添加唯一分隔符作为标识符将其保留为单个字符串。例如
{这是第一行^^这是第二行}
然后在您的消费者作业中相应地处理消息。即使客户端计划在消息中发送多个句子,最好将其发送到单个字符串中,这样可以提高消息的序列化效果,序列化后效率更高。
您可以为此使用 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
请注意,分隔符 必须 是单个字节 - 多字节字符最终将包含在结果消息中 See issue #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
使用 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!
(因此说明了为什么 kafkacat
比 kafka-console-consumer
更好用,因为它的可选冗长 :) )
我想将包含多行的文本作为一条消息推送到 kafka 主题中。
我输入后:
kafka-console-producer --broker-list localhost:9092 --topic myTopic
并复制我的文字:
My Text consists of:
two lines instead of one
我在 kafka 主题中收到两条消息,但我只想收到一条消息。任何想法如何实现?谢谢
kafka-console-producer
不可能,因为它使用 Java 以换行符分隔的扫描仪对象。
您需要通过自己的生产者代码来完成
对于 Console-consumer,您显然是在 运行 测试来自客户端的预期数据。如果它是单个消息,最好通过添加唯一分隔符作为标识符将其保留为单个字符串。例如
{这是第一行^^这是第二行}
然后在您的消费者作业中相应地处理消息。即使客户端计划在消息中发送多个句子,最好将其发送到单个字符串中,这样可以提高消息的序列化效果,序列化后效率更高。
您可以为此使用 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
请注意,分隔符 必须 是单个字节 - 多字节字符最终将包含在结果消息中 See issue #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
使用 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!
(因此说明了为什么 kafkacat
比 kafka-console-consumer
更好用,因为它的可选冗长 :) )