Search code examples
spring-cloud-streamspring-cloud-stream-binder-kafka

Spring Cloud Stream: consumer for different message types


With a StreamBridge I send messages with two different types of objects to a single Kafka topic. Is there a way to define a functional consumer with Spring Cloud Stream capable of consuming both types of messages?


Solution

  • Using the event routing feature, you can have multiple consumers and then route to the right consumer using the routing function. See this sample for something more advanced. However, I realize that this is not your use case, but wanted to mention it just in case. On the consumer side, having multiple types accepted is hard if using domain objects. For example, if your incoming POJO is Foo (Consumer<Foo>), it will fail on deserialization if you are sending Bar to it. If you are willing to accept Consumer<byte[], then you can just use a ByteArrayDeserializer and then turn on native decoding in the app, so that no conversion is attempted. Once you receive your byte[], then you can maybe trying to use an ObjectMappter or similar mechanism to build your actual object with the proper type.