我是否必须使用@Payload spring 注释来读取 Kafka 消息
Do I have to use @Payload spring annotation to read Kafka message
Spring for Apache Kafka 2.8.4 under https://docs.spring.io/spring-kafka/reference/html 显示了消息旁边带有 @Payload
注释的一些侦听器方法,有些则没有。例如:
@KafkaListener(id = "cat", topics = "myTopic",
containerFactory = "kafkaManualAckListenerContainerFactory")
public void listen(String data, Acknowledgment ack) {
...
ack.acknowledge();
}
和
@KafkaListener(id = "qux", topicPattern = "myTopic1")
public void listen(@Payload String foo,
@Header(name = KafkaHeaders.RECEIVED_MESSAGE_KEY, required = false) Integer key,
@Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
@Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
@Header(KafkaHeaders.RECEIVED_TIMESTAMP) long ts
) {
...
}
哪种做法是正确的?我正在测试两者,看不出有什么不同。
简短的回答是否定的,您不必使用它。
长答案是“视情况而定”;如果你想对 Kafka 消息做一些验证,@Payload
会帮助你;喜欢 spring doc
中的以下内容
To configure the @KafkaListener to handle null payloads, you must use the @Payload annotation with required = false. If it is a tombstone message for a compacted log, you usually also need the key so that your application can determine which key was “deleted”. The following example shows such a configuration:
我宁愿使用普通字符串,这样您就可以通过将责任卸载到应用程序端而不是 built-in 处理的方式来避免一些已知的解析问题,例如 Poison Pill Spring.
Spring for Apache Kafka 2.8.4 under https://docs.spring.io/spring-kafka/reference/html 显示了消息旁边带有 @Payload
注释的一些侦听器方法,有些则没有。例如:
@KafkaListener(id = "cat", topics = "myTopic",
containerFactory = "kafkaManualAckListenerContainerFactory")
public void listen(String data, Acknowledgment ack) {
...
ack.acknowledge();
}
和
@KafkaListener(id = "qux", topicPattern = "myTopic1")
public void listen(@Payload String foo,
@Header(name = KafkaHeaders.RECEIVED_MESSAGE_KEY, required = false) Integer key,
@Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
@Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
@Header(KafkaHeaders.RECEIVED_TIMESTAMP) long ts
) {
...
}
哪种做法是正确的?我正在测试两者,看不出有什么不同。
简短的回答是否定的,您不必使用它。
长答案是“视情况而定”;如果你想对 Kafka 消息做一些验证,@Payload
会帮助你;喜欢 spring doc
To configure the @KafkaListener to handle null payloads, you must use the @Payload annotation with required = false. If it is a tombstone message for a compacted log, you usually also need the key so that your application can determine which key was “deleted”. The following example shows such a configuration:
我宁愿使用普通字符串,这样您就可以通过将责任卸载到应用程序端而不是 built-in 处理的方式来避免一些已知的解析问题,例如 Poison Pill Spring.