Video in progress

Strong Middle 📨 Kafka and messaging

One topic carries several event types (`OrderCreated`, `OrderPaid`, `OrderCancelled`). How do you receive them in Spring Kafka?

I put @KafkaListener at the class level and a separate @KafkaHandler method for each type; Spring calls the right method based on the payload type. For that, the deserializer must know the exact Java type, through a type header or type mapping.

📖 Answer

For all events of one order to arrive in order, they live in one topic with one key. On the consumer side you need separate logic for each type:

@Component
@KafkaListener(topics = "orders", groupId = "notifications")
class OrderEventsListener {

    @KafkaHandler
    void created(OrderCreated e) { mail.welcome(e.customerId()); }

    @KafkaHandler
    void paid(OrderPaid e) { mail.receipt(e.orderId()); }

    @KafkaHandler(isDefault = true)
    void other(Object e) {
        // if a new type is added, the consumer shouldn't crash
        log.debug("E'tiborsiz qoldirildi: {}", e.getClass().getSimpleName());
    }
}

The deserialization part matters more. JsonDeserializer has to know which class to convert to. Since the packages differ between the producer and the consumer, I use a short token instead of the class name:

spring:
  kafka:
    consumer:
      properties:
        spring.json.type.mapping: >-
          orderCreated:com.shop.notify.OrderCreated,
          orderPaid:com.shop.notify.OrderPaid

The producer gets a mapping with the same tokens, so what travels in the header is orderCreated, not internal package names.

Don't forget to add the isDefault = true handler. Without it, the day the producer adds a new OrderRefunded type, your consumer ends up in the error handler with a "no handler" error. With Avro/Protobuf and Schema Registry, the type information comes from the schema and the approach is slightly different, but the idea is the same.