Messaging and Spring JMS with Spring Boot

📬 What is Messaging?

Messaging allows different parts of an application (or different systems) to communicate asynchronously via a message queue.

Instead of one system calling another directly, it sends a message to a queue, and the other system picks it up later.


💡 Why Use Messaging?

  • Systems stay loosely coupled
  • Improves scalability and fault tolerance
  • Handles delays or failures more gracefully
  • Great for event-driven architectures and microservices

🚀 What is JMS?

JMS = Java Message Service
It’s a standard Java API for sending and receiving messages via a Message Broker (like ActiveMQ, RabbitMQ, etc.)


🛠 What is Spring JMS?

Spring JMS makes it easy to use JMS in Spring Boot.
It simplifies sending and receiving messages from a message queue.


✅ Messaging Example with ActiveMQ + Spring Boot

🔗 Step 1: Add Dependencies (pom.xml)

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

⚙️ Step 2: Configuration (application.properties)

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin

📤 Step 3: Message Producer

@Service
public class MessageSender {

    @Autowired
    private JmsTemplate jmsTemplate;

    public void sendMessage(String destination, String message) {
        jmsTemplate.convertAndSend(destination, message);
    }
}

 


📥 Step 4: Message Listener (Consumer)

@Component
public class MessageReceiver {

    @JmsListener(destination = "test-queue")
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

 

🧪 Test the Messaging

@RestController
public class MessageController {

    @Autowired
    private MessageSender sender;

    @GetMapping("/send")
    public String send() {
        sender.sendMessage("test-queue", "Hello from Spring JMS!");
        return "Message Sent!";
    }
}

 

📦 Message Brokers You Can Use

Broker Description
ActiveMQ Open-source, widely used with JMS
RabbitMQ Fast, supports AMQP (non-JMS)
Kafka High-throughput event streaming
Amazon SQS Fully managed queue service (cloud)

🧠 Summary

Feature Spring JMS Benefit
Easy Config Auto-setup with Spring Boot
Asynchronous Better performance, non-blocking
Scalable Works well in microservices architecture
Simple API JmsTemplate to send, @JmsListener to receive
Back to blog

Leave a comment