activemq.org › Handbook › ActiveMQ tutorial: send and receive your first messages
HandbookActiveMQ tutorial: send and receive your first messages
This ActiveMQ tutorial starts a broker, sends test messages from the command line, then sends and receives messages from Java on a queue and on a topic, and finishes with a short Python client over STOMP. The Java code follows the official OpenWire examples that ship with ActiveMQ (the examples/ directory of the distribution, also in the apache/activemq repository on GitHub) and targets ActiveMQ 6.4.0 with the Jakarta jakarta.jms API.
What you need
- ActiveMQ installed and unpacked: see install ActiveMQ, or run it in a container with ActiveMQ in Docker. The 6.4.x series needs Java 17 to 25; 5.19.x runs on Java 11 to 22.
- A JDK and Maven (or Gradle) for the Java steps.
- Python 3.10 or newer for the optional Python step (the current stomp.py release, 9.0.0, requires it).
The official documentation for everything below is at activemq.apache.org.
Step 1: Start the broker
From the ActiveMQ installation directory, start the broker in the foreground so its log stays on screen. From the ActiveMQ getting-started guide, for Linux and macOS; the commands are the same for 6.4.0 and 5.19.x:
cd apache-activemq-6.4.0/bin
./activemq console
On Windows, the same guide starts it from the installation directory with bin\activemq start. Stop the broker with Ctrl-C in the window where it runs.
The broker now accepts OpenWire clients on port 61616. Open the web console at http://localhost:8161/admin and log in with the default username and password, admin/admin. Change that login before the broker is reachable by anyone else (see the web console page).
Step 2: Send and receive from the command line
Since version 5.12.0 the activemq script includes a test producer and consumer, so you can check the broker before writing code. Open a second terminal in the installation directory. These commands follow the ActiveMQ examples page:
bin/activemq producer --message "Hello ActiveMQ" --messageCount 10
bin/activemq consumer --messageCount 10
Without --destination, both commands use the queue TEST, and they default to 1,000 messages, which is why the example sets --messageCount. Open Queues in the web console to see the TEST queue and its counters. Run bin/activemq producer --help for the other options.
To see a topic instead, start the consumer first, because a topic only delivers to subscribers that are already listening. Same tool, with the topic:// destination syntax from the examples page:
bin/activemq consumer --destination topic://news --messageCount 1
bin/activemq producer --destination topic://news --message "Hello subscribers" --messageCount 1
Step 3: Add the ActiveMQ client to a Java project
The client library is org.apache.activemq:activemq-client on Maven Central. Use the version that matches your broker series. For ActiveMQ 6.4.0 (coordinates as on the 6.4.0 release page, which names activemq-client as one of the modules you can depend on):
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-client</artifactId>
<version>6.4.0</version>
</dependency>
In 6.4.0, activemq-client depends on jakarta.jms:jakarta.jms-api, so your code imports jakarta.jms.*. If your broker is on the 5.19.x series, use a 5.19.x client instead, and import javax.jms.*; the 5.19.12 copy of the same examples does exactly that. Mixing the two (6.x client with javax.jms imports, or the reverse) will not compile.
Step 4: Send messages to a queue
Shortened from Producer.java in the jms-example-queue example of ActiveMQ 6.4.0 (examples/openwire/advanced-scenarios). The broker URL, credentials, queue name and message text are the example's; the loop count and error handling are reduced:
package example.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import jakarta.jms.*;
public class Producer {
private static final String BROKER_URL = "tcp://localhost:61616";
public static void main(String[] args) throws JMSException {
ActiveMQConnectionFactory connectionFactory =
new ActiveMQConnectionFactory("admin", "password", BROKER_URL);
Connection connection = connectionFactory.createConnection();
try {
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("test-queue");
MessageProducer producer = session.createProducer(destination);
for (int i = 0; i < 10; i++) {
TextMessage message = session.createTextMessage("Message #" + i);
System.out.println("Sending message #" + i);
producer.send(message);
}
} finally {
connection.close();
}
}
}
The pattern is the same in every JMS program: a connection factory creates a connection, the connection creates a session (here non-transacted, with automatic acknowledgement), and the session creates the destination, producers and consumers. The example passes the username admin and password password; change them to match your broker if you have turned on authentication.
Step 5: Receive messages from the queue
Shortened from Consumer.java in the same example. It waits up to 20 seconds for each message and stops when none arrives:
package example.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import jakarta.jms.*;
public class Consumer {
private static final String BROKER_URL = "tcp://localhost:61616";
private static final long TIMEOUT = 20000;
public static void main(String[] args) throws JMSException {
ActiveMQConnectionFactory connectionFactory =
new ActiveMQConnectionFactory("admin", "password", BROKER_URL);
Connection connection = connectionFactory.createConnection();
try {
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("test-queue");
MessageConsumer consumer = session.createConsumer(destination);
while (true) {
Message message = consumer.receive(TIMEOUT);
if (message == null) {
break;
}
if (message instanceof TextMessage) {
System.out.println("Got message: " + ((TextMessage) message).getText());
}
}
} finally {
connection.close();
}
}
}
Run the producer, then the consumer: the messages were waiting on the queue. Then start two consumers and run the producer again. Each message goes to exactly one of them, which is how a queue spreads work across workers. To run the unmodified example instead, its readme says to run mvn install, then mvn -Pconsumer in one terminal and mvn -Pproducer in another.
Step 6: Publish and subscribe with a topic
The jms-example-topic example uses the same setup with session.createTopic("test-topic"). Its subscriber registers a MessageListener instead of calling receive(), and the publisher sends a final END message so subscribers know when to stop. The listener part, from Subscriber.java in ActiveMQ 6.4.0:
Destination destination = session.createTopic("test-topic");
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new Subscriber(latch));
// ...
@Override
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
String text = ((TextMessage) message).getText();
if ("END".equalsIgnoreCase(text)) {
System.out.println("Received END message!");
countDownLatch.countDown();
}
else {
System.out.println("Received message:" +text);
}
}
} catch (JMSException e) {
System.out.println("Got a JMS Exception!");
}
}
Start one or more subscribers before the publisher. Every subscriber gets its own copy of each message, but only subscribers with an active subscription when a message arrives receive it. If a subscriber must not miss messages while it is offline, use a durable subscription; the jms-example-durable-sub example in the same folder shows how. The message queue page compares the two models.
Step 7: Use ActiveMQ from Python with STOMP
Non-Java programs usually connect through STOMP, AMQP or MQTT rather than OpenWire. In the default conf/activemq.xml of ActiveMQ 6.4.0, 6.3.3 and 5.19.12 those connectors are commented out, so enable STOMP first. Remove the comment markers around this line from the 6.4.0 file, then restart the broker:
<transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&wireFormat.maxFrameSize=10485760"/>
Install the client with pip install stomp.py. This is the quick-start example from the stomp.py documentation (the 8.3.0 docs linked from the 9.0.0 release); it subscribes to a queue, sends one message to it and prints what arrives:
import time
import sys
import stomp
class MyListener(stomp.ConnectionListener):
def on_error(self, frame):
print('received an error "%s"' % frame.body)
def on_message(self, frame):
print('received a message "%s"' % frame.body)
conn = stomp.Connection()
conn.set_listener('', MyListener())
conn.connect('admin', 'password', wait=True)
conn.subscribe(destination='/queue/test', id=1, ack='auto')
conn.send(body=' '.join(sys.argv[1:]), destination='/queue/test')
time.sleep(2)
conn.disconnect()
Save it as stomptest.py and run python stomptest.py this is a test. stomp.Connection() connects to localhost on the default STOMP port, 61613. ActiveMQ strips the /queue/ or /topic/ prefix, so /queue/test is the JMS queue test, and a Java consumer on session.createQueue("test") reads the same messages. More on STOMP, stomp.py and OpenWire: STOMP protocol.
Common problems
- Connection refused on port 61616. The broker is not running or is on another host. Check the broker output or
data/activemq.login the installation directory, and check the port withnetstat -nl | grep 61616(Windows:netstat -an | find "61616"). - Python or another STOMP client cannot connect on 61613. The STOMP connector is commented out by default in current releases; enable it as in step 7 and restart.
- The topic subscriber prints nothing. It was started after the publisher. Non-durable subscribers only receive messages published while they are subscribed.
- The consumer finds no messages but the console shows some. Check the destination name. The command-line tools default to
TEST, the Java example usestest-queue, and the Python example usestest. - Imports do not compile. The client series and the JMS package must match:
jakarta.jmswith 6.x,javax.jmswith 5.19.x.
Where to go next
- Use ActiveMQ from Spring with
JmsTemplate: ActiveMQ with Spring Boot. - Handle messages that keep failing: dead letter queues.
- Watch queues and consumers: ActiveMQ monitoring.
- For history, the 2006 archive page on getting started is at /site/getting-started.html; its commands predate the current releases.
Frequently asked questions
How do I send a test message to ActiveMQ from the command line?
From the ActiveMQ directory run bin/activemq producer --message "Hello" --messageCount 1, and read it back with bin/activemq consumer --messageCount 1. Without --destination both commands use the queue TEST on the local broker.
What is the difference between a queue and a topic in ActiveMQ?
A queue delivers each message to exactly one consumer and keeps it until a consumer is available. A topic delivers a copy to every subscriber that has an active subscription when the message arrives; durable subscriptions also keep messages for subscribers that are offline.
Which Java dependency do I need for ActiveMQ 6?
Add org.apache.activemq:activemq-client for your broker series, for example version 6.4.0. In 6.x it brings the Jakarta Messaging API, so your code imports jakarta.jms. For a 5.19.x broker use a 5.19.x client and javax.jms imports.
Can I use ActiveMQ from Python?
Yes. The common route is STOMP with the stomp.py library. In ActiveMQ 6.4.0, 6.3.3 and 5.19.12 the STOMP connector on port 61613 is commented out in conf/activemq.xml, so enable it and restart the broker first.
Where are the official ActiveMQ examples?
The ActiveMQ distribution has an examples directory, and the same files are in the apache/activemq repository on GitHub. They include OpenWire Java examples for queues, topics, durable subscriptions and transactions, plus STOMP, AMQP and MQTT clients.
Related guides
- How to install ActiveMQ on Ubuntu, Windows and macOS
- ActiveMQ Spring Boot setup: starter, JmsTemplate and @JmsListener
- STOMP protocol explained, with ActiveMQ, RabbitMQ and Python
- What is a message queue? Queues, topics and publish/subscribe
- ActiveMQ web console: URL, login and password
- All handbook guides
From the 2006 archive
The original ActiveMQ documentation on these topics, kept as it was published here in 2004–2007. It describes ActiveMQ 4.x and older.
Sources
- Getting Started with ActiveMQ activemq.apache.org
- ActiveMQ: Examples (producer and consumer tool) activemq.apache.org
- ActiveMQ 6.4.0 OpenWire examples: jms-example-queue (GitHub) github.com
- ActiveMQ 6.4.0 OpenWire examples: jms-example-topic (GitHub) github.com
- ActiveMQ FAQ: How does a Queue compare to a Topic activemq.apache.org
- ActiveMQ: STOMP activemq.apache.org
- stomp.py documentation: Quick start jasonrbriggs.codeberg.page
- ActiveMQ 6.4.0 release (Maven coordinates) activemq.apache.org