如何使用 Header 从一条 Kafka 消息中获取多个 objects

How to get multiple objects from one Kafka message using Header

我想从一条消息(来自同一主题)中反序列化不同的 object,并根据 object 将其键入 save/update 到适当的 table 中D B。正如加里提到的 here 我可以使用 headers 来提供我的 object 必须反序列化到哪种类型的信息。你能举例说明如何实现这一目标吗?

参见示例 02 here

Sample 2

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).

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.

The MultiMethods @KafkaListener has 3 methods; one for each of the known objects and a fallback default method for others.

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

Console:

Received: Foo2 [foo=bar]

Received: Bar2 [bar=baz]

Received unknown: xxx