英文:
Spring Kafka Consumer printing incorrect headers
问题
以下是您要的翻译:
public final class KafkaConsumer {
@KafkaListener(
topics = "${event.consumer.topics}",
groupId = "${event.consumer.groupId}",
containerFactory = "kafkaListenerFactory")
public void receive(
ConsumerRecord<String, Object> consumerRecord,
@Header("foo") String foo,
@Headers Map<String, String> header,
Acknowledgment acknowledgment) {
try {
System.out.println(foo);
System.out.println(header.get("foo"));
acknowledgment.acknowledge();
} catch (Exception e) {
e.printStackTrace();
}
}
}
第一个打印语句会输出正确的值(bar),但第二个语句会输出一些垃圾值([B@5f1af89d)。请问有人可以告诉我如何正确地将标头作为映射读取吗?
英文:
I am using Spring Boot's KafkaListener to consume events from a Kafka topic. I am interested in reading the headers for the events. I am able to get the correct value of individual headers when I read them individually but when I try to read it as a map, the values seem different.
This is what my code looks like:
public final class KafkaConsumer {
@KafkaListener(
topics = "#{'${event.consumer.topics}'.split(',')}",
groupId = "${event.consumer.groupId}",
containerFactory = "kafkaListenerFactory")
public void receive(
ConsumerRecord<String, Object> consumerRecord,
@Header("foo") String foo,
@Headers Map<String, String> header,
Acknowledgment acknowledgment) {
try {
System.out.println(foo);
System.out.println(header.get("foo");
acknowledgment.acknowledge();
} catch (Exception e) {
e.printStackTrace();
}
}
The first print statement gives the correct value (bar) but the second statement prints some garbage ([B@5f1af89d). Can someone let me know how to read the headers correctly as a map?
答案1
得分: 2
[B@5f1af89d 是对 byte[] 上的 toString() 的结果。通过 Kafka 发送的标头是 byte[]。使用 new String(header.get("foo"))。
话虽如此,id 标头是一个 UUID,而不是 byte[],它是在本地创建的,所以你的问题似乎有些问题。你说你正在发送标头 foo,但你却打印了 id。
英文:
[B@5f1af89d is the result of toString() on a byte[]. Headers sent over Kafka are byte[]. Use new String(header.get("foo")).
That said, the id header is a UUID, not byte[], and it is created locally so there is something amiss in your question. You say you are sending header foo but you are printing id.
答案2
得分: 0
这些垃圾看起来就像来自不提供实现的对象的'toString'输出,或者来自数组类型。
我建议查看调试器中的头对象,以了解发生了什么。可能需要声明为<String, Object>或其他类型。这个练习还应该帮助您了解您的生产者是否在正确地执行。
英文:
That garbage looks to me just like the output of 'toString' from an Object that does not provide an implementation, or from an Array type.
I'd suggest taking a look at the header object in a Debugger to understand what's going on. It might need to be declared as <String, Object> or something. This exercise should also help you know if your producer is doing the right thing or not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论