在Kafka中发送ProducerRecord所需的Serilizer类型

时间:2017-12-11 19:31:10

标签: apache-kafka spring-kafka

我正在使用spring kafka(KafkaTemplate)发送字符串消息。但为了使它与旧代码兼容,我需要在消息中附加额外的CorrelationId。所以我用我的消息作为其值创建ProducerRecord对象,并在其HeaderRecord中设置CorrelationId。

        producerRecord = new ProducerRecord<>(
            kafkaTemplate_.getDefaultTopic(),
            null,
            null,
            null,
            myStringMessage,
            Collections.singletonList(new RecordHeader("CorrelationID", someIdAsBytes)));
    kafkaTemplate_.sendDefault(producerRecord);

key和value序列化程序设置为StringSerializer,但是关于代码的错误说明类似于ProduderRecord的类型不是String或StringSerializer。

如果我像下面那样使用toString(),它就可以了。但是在MessageListener端,收到的ConsumerRecord没有将correlationId作为其RecordHeader,因为correlationId被附加为ProducerRecord的RecordHeader。所以我必须在MessageListener onMessage(Object msg)上进行类型转换,例如从Object转换为ConsumerRecord(这是ProduderRecord的字符串序列化版本),从ConsumerRecord.value()字段解析ProducerRecord,然后从ProcuderRecord头获取CorrelationId,并且来自ProducerRecord的myStringMessage。这看起来很麻烦。我发送和接收的逻辑是否正确?

kafkaTemplate_.sendDefault(producerRecord.toString());

1 个答案:

答案 0 :(得分:2)

看起来你只是错过了区别:

/**
 * Send the data to the default topic with no key or partition.
 * @param data The data.
 * @return a Future for the {@link SendResult}.
 */
ListenableFuture<SendResult<K, V>> sendDefault(V data);

/**
 * Send the provided {@link ProducerRecord}.
 * @param record the record.
 * @return a Future for the {@link SendResult}.
 * @since 1.3
 */
ListenableFuture<SendResult<K, V>> send(ProducerRecord<K, V> record);

请注意,topic中有ProducerRecord个属性,因此,没有理由考虑sendDefault()。另外,正如您所看到的那样令您感到困惑。