【问题标题】:push multiple Line Text as one message in a kafka topic将多行文本作为一条消息推送到 kafka 主题中
【发布时间】:2018-09-04 17:25:00
【问题描述】:

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

我进入后:

kafka-console-producer --broker-list localhost:9092 --topic myTopic

并复制我的文字:

My Text consists of:
two lines instead of one

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

【问题讨论】:

    标签: apache-kafka kafka-producer-api


    【解决方案1】:

    您可以为此使用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!
    

    因此说明了为什么kafkacatkafka-console-consumer 更易于使用,因为它的可选冗长:)

    【讨论】:

      【解决方案2】:

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

      你需要通过你自己的生产者代码来做这件事

      【讨论】:

        【解决方案3】:

        使用 Console-consumer,您显然正在为来自客户端的预期数据运行测试。如果它是单个消息,最好通过添加唯一分隔符作为标识符将其保留为单个字符串。例如

        {这是第一行^^这是第二行}

        然后在您的消费者工作中相应地处理消息。即使客户端计划在消息中发送多个句子,最好将其放在单个字符串中,这将改善您的消息的序列化,并且序列化后效率更高。

        【讨论】:

        • 最好不要依赖消息中的随机分隔符
        • 同意,实际上如果测试用例包含多行,则使用“\n”分隔符来模拟这种情况。例如{这是第一行 \n 这是第二行}
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-20
        • 2019-10-09
        • 2020-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        相关资源
        最近更新 更多