Introduction to Message Middleware and ActiveMQ: Scenarios, Transmission Modes, and Spring Boot Integration
This article introduces the fundamentals of message middleware, explains its key application scenarios such as asynchronous processing, system decoupling, flow control, and distributed transaction consistency, details the three transmission modes (point‑to‑point, publish/subscribe, request‑reply), and provides a step‑by‑step ActiveMQ quick‑start guide with Spring Boot integration and complete Java code examples.
Message middleware is an essential component in large distributed systems, offering solutions for asynchronous processing, system decoupling, traffic shaping, and distributed transaction management. The article covers three main topics: application scenarios, transmission modes, and an ActiveMQ quick‑start tutorial.
Message Middleware Application Scenarios
Asynchronous Processing : The caller sends a request without waiting for an immediate result, improving efficiency for non‑core business logic such as email verification after user registration.
System Decoupling and Transaction Consistency : By routing order data through a message queue, the order service and warehouse service operate independently, and eventual consistency is achieved for inventory updates.
Traffic Shaping (Rate Limiting) : In high‑traffic events like flash sales, a message queue can limit request bursts, protecting system stability.
Message Middleware Transmission Modes
Point‑to‑Point (P2P) : Involves a queue, a sender, and a receiver. Each message is consumed by a single receiver, and the sender and receiver are loosely coupled.
Publish/Subscribe (Pub/Sub) : Uses a topic, publishers, and multiple subscribers. Messages can be consumed by many subscribers, with options for persistent or non‑persistent subscriptions.
Request‑Reply (Bidirectional) : An enhanced mode where the sender also acts as a receiver, enabling two‑way communication.
ActiveMQ Quick Start
ActiveMQ is an Apache‑maintained open‑source message broker that implements the JMS specification.
JMS (Java Message Service) is a standard API for sending, receiving, and creating messages, reducing coupling and increasing reliability in distributed applications.
Installation
1. Download from the official site. 2. Extract and run the appropriate wrapper.exe in the bin directory. 3. Access the admin console at http://localhost:8161/admin (default credentials admin/admin).
ActiveMQ Workflow (P2P Example)
The producer creates a connection factory, opens a connection, starts it, creates a session, defines a queue, creates a message producer, sends a message, and finally closes resources.
import java.util.Random;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
* 消息队列生产者
*/
public class ITDragonProducer {
private static final String QUEUE_NAME = "ITDragon.Queue";
public static void main(String[] args) {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageProducer producer = null;
try {
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD, ActiveMQConnection.DEFAULT_BROKER_URL);
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(QUEUE_NAME);
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// send messages ...
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (connection != null) connection.close(); } catch (Exception e) { e.printStackTrace(); }
}
}
// sendMessage method omitted for brevity
}The consumer mirrors the producer steps, replacing MessageProducer with MessageConsumer and using receive() to obtain messages.
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
* 消息队列消费者
*/
public class ITDragonConsumer {
private static final String QUEUE_NAME = "ITDragon.Queue";
public static void main(String[] args) {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageConsumer consumer = null;
try {
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD, ActiveMQConnection.DEFAULT_BROKER_URL);
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(QUEUE_NAME);
consumer = session.createConsumer(destination);
while (true) {
TextMessage message = (TextMessage) consumer.receive();
if (message != null) {
System.out.print(ITDragonUtil.cal(message.getText()));
} else {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (connection != null) connection.close(); } catch (Exception e) { e.printStackTrace(); }
}
}
}Spring Boot Integration
Adding the spring-boot-starter-activemq dependency and configuring application.properties enables rapid setup.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>Properties example:
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.in-memory=true
spring.activemq.pool.enabled=trueTwo core components are demonstrated: a producer service that periodically sends messages to a queue, a topic, and a response queue, and a consumer service that listens to these destinations using @JmsListener annotations.
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Service;
@Service
public class ITDragonConsumer {
@JmsListener(destination = "queue.name", containerFactory="queueListenerFactory")
public void receiveQueue(String text) {
System.out.println("Queue Receiver : " + text + " \t 处理结果 : " + ITDragonUtil.cal(text));
}
@JmsListener(destination = "topic.name", containerFactory="topicListenerFactory")
public void receiveTopicOne(String text) {
System.out.println(Thread.currentThread().getName() + " No.1 Topic Receiver : " + text + " \t 处理结果 : " + ITDragonUtil.cal(text));
}
@JmsListener(destination = "topic.name", containerFactory="topicListenerFactory")
public void receiveTopicTwo(String text) {
System.out.println(Thread.currentThread().getName() + " No.2 Topic Receiver : " + text + " \t 处理结果 : " + ITDragonUtil.cal(text));
}
@JmsListener(destination = "response.name")
@SendTo("out.queue")
public String receiveResponse(String text) {
System.out.println("Response Receiver : " + text + " \t 正在返回数据......");
return ITDragonUtil.cal(text).toString();
}
}Bean configuration defines the queue, topic, and response queue objects using ActiveMQQueue and ActiveMQTopic , while a separate JmsConfig class creates listener factories for P2P and Pub/Sub modes.
Conclusion
Message middleware solves asynchronous processing, system coupling, traffic spikes, and distributed transaction challenges. ActiveMQ provides a simple yet powerful JMS‑compatible broker, supporting point‑to‑point, publish/subscribe, and request‑reply patterns, and integrates seamlessly with Spring Boot for rapid development.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.