A message listener is a method or component invoked when a message arrives at a messaging destination. It uses a push model: the messaging framework delivers available messages instead of making application code wait for them. section 9.1.3
Spring listeners commonly receive an already-converted domain object and pass it to application logic. JMS uses @JmsListener, while Kafka uses @KafkaListener; both identify the destination and the method to invoke. section 9.1.3 section 9.3.3
A listener method can receive:
- The converted message payload, such as TacoOrder, for ordinary application processing. section 9.1.3 section 9.3.3
- Transport metadata through a ConsumerRecord or Message, including Kafka partition and timestamp information. section 9.3.3
- A push-based workload, although a pull model may suit consumers that must control when they process another message. section 9.1.3
Displaying incoming orders
A component annotated with @JmsListener(destination = "tacocloud.order.queue") can receive a TacoOrder and call ui.displayOrder(order). The Kafka equivalent annotates a handle method with @KafkaListener(topics = "tacocloud.orders.topic"). section 9.1.3 section 9.3.3
Listing 9.4 An OrderListener component that listens for orders
package tacos.kitchen.messaging.jms.listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import tacos.TacoOrder;
import tacos.kitchen.KitchenUI;
@Profile("jms-listener")
@Component
public class OrderListener {
private KitchenUI ui;
@Autowired
public OrderListener(KitchenUI ui) {
this.ui = ui;
}
@JmsListener(destination = "tacocloud.order.queue")
public void receiveOrder(TacoOrder order) {
ui.displayOrder(order);
}
}
Browse a complete JMS listener component showing dependency injection, profile selection, destination binding, and order handling. section 9.1.3
Listing 9.9 Receiving orders with @KafkaListener
package tacos.kitchen.messaging.kafka.listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import tacos.Order;
import tacos.kitchen.KitchenUI;
@Component
public class OrderListener {
private KitchenUI ui;
@Autowired
public OrderListener(KitchenUI ui) {
this.ui = ui;
}
@KafkaListener(topics="tacocloud.orders.topic")
public void handle(TacoOrder order) {
ui.displayOrder(order);
}
}
Browse a complete Kafka listener showing topic binding and direct delivery of a converted TacoOrder payload. section 9.3.3
