如何使用标题从一则Kafka消息中获取多个对象 [英] How to get multiple objects from one Kafka message using Header

查看:70
本文介绍了如何使用标题从一则Kafka消息中获取多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一条消息(来自同一主题)反序列化不同的对象,并根据对象类型将其保存/更新到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?

推荐答案

请参见sample-02

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 and Bar1 and the consumer receives objects of type Foo2 and Bar2 (the objects have the same field, foo).

生产者使用 JsonSerializer ;使用者使用 ByteArrayDeserializer ByteArrayJsonMessageConverter 一起将其转换为所需的侦听器方法参数类型.在这种情况下,我们无法推断类型(因为该类型用于选择要调用的方法).因此,我们在生产者和消费者方面配置类型映射.有关生产者方面的信息,请参见 application.yml ;有关消费者方面的信息,请参见 converter bean.

The producer uses a JsonSerializer; the consumer uses a ByteArrayDeserializer, together with a ByteArrayJsonMessageConverter 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 the application.yml for the producer side and the converter 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆