Jakarta Messaging is the standard Java programming model commonly called JMS here. It gives applications a common API for sending and receiving messages through compliant brokers, rather than tying messaging code to one broker’s proprietary API. In Spring, JmsTemplate provides a practical way to send to queues or topics and receive from them. section 9.1
Start with a running broker and a matching Spring Boot starter. ActiveMQ and ActiveMQ Artemis use different starters and connection settings, but the choice has little effect on message-sending and receiving code. For Artemis, Spring assumes localhost port 61616 during development; configure the host, port, and optionally credentials for another deployment. section 9.1.1
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-artemis</artifactId> </dependency>
Add this Maven starter when using an ActiveMQ Artemis broker. section 9.1.1
A kitchen receiving orders from a queue can choose how to take delivery:
- Pull with JmsTemplate.receive(): request a raw Message and convert it to a TacoOrder. The call blocks until a message is available. section 9.1.3
- Pull with receiveAndConvert(): request an object converted using the configured message converter. section 9.1.3
- Push with a @JmsListener method: have Spring invoke the method as messages arrive. This avoids a blocked receiving thread, though a listener may be overburdened by messages arriving too quickly. section 9.1.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);
}
}
This listener receives TacoOrder values from tacocloud.order.queue and passes them to the kitchen UI. section 9.1.3
