如何使用标题从一则Kafka消息中获取多个对象 [英] How to get multiple objects from one Kafka message using Header
问题描述
我想从一条消息(来自同一主题)反序列化不同的对象,并根据对象类型将其保存/更新到DB中的适当表.正如Gary在此处所述,我可以使用标头来提供我的对象必须反序列化为哪种类型的信息.您可以提供有关实现此目标的示例的帮助吗?
I want to deserialize different objects from one message (from the same topic), and according to object type save/update it to the appropriate table in DB. As Gary mentioned here I can use headers to provide information to which type my object must be deserialized. Can you help with examples of how to achieve this?
推荐答案
See sample-02 here.
示例2
此样本演示了一个简单的生产者和一个多方法的消费者;生产者发送类型为
Foo1
和Bar1
的对象,而消费者接收类型为Foo2
和Bar2
的对象(这些对象具有相同的字段foo
).
This sample demonstrates a simple producer and a multi-method consumer; the producer sends objects of types
Foo1
andBar1
and the consumer receives objects of typeFoo2
andBar2
(the objects have the same field,foo
).
生产者使用
JsonSerializer
;使用者使用ByteArrayDeserializer
和ByteArrayJsonMessageConverter
一起将其转换为所需的侦听器方法参数类型.在这种情况下,我们无法推断类型(因为该类型用于选择要调用的方法).因此,我们在生产者和消费者方面配置类型映射.有关生产者方面的信息,请参见application.yml
;有关消费者方面的信息,请参见converter
bean.
The producer uses a
JsonSerializer
; the consumer uses aByteArrayDeserializer
, together with aByteArrayJsonMessageConverter
which converts to the required type of the listener method argument. We can't infer the type in this case (because the type is used to choose the method to call). We therefore configure type mapping on the producer and consumer side. See theapplication.yml
for the producer side and theconverter
bean on the consumer side.
MultiMethods
@KafkaListener
有3种方法;一个为每个已知对象,另一个为后备默认方法.
The
MultiMethods
@KafkaListener
has 3 methods; one for each of the known objects and a fallback default method for others.
运行该应用程序并使用curl发送一些数据:
Run the application and use curl to send some data:
$ curl -X POST http://localhost:8080/send/foo/bar
$ curl -X POST http://localhost:8080/send/bar/baz
$ curl -X POST http://localhost:8080/send/unknown/xxx
控制台:
已接收:Foo2 [foo = bar]
已接收:Bar2 [bar = baz]
接收到的未知数:xxx
这篇关于如何使用标题从一则Kafka消息中获取多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!