
| 層級 | PTP 接口 | Pub/Sub 接口 | 統一域接口 (JMS 1.1+) |
|---|---|---|---|
| ConnectionFactory | QueueConnectionFactory | TopicConnectionFactory | ConnectionFactory |
| Connection | QueueConnection | TopicConnection | Connection |
| Session | QueueSession | TopicSession | Session |
| Destination | Queue | Topic | Destination |
| Producer | QueueSender | TopicPublisher | MessageProducer |
| Consumer | QueueReceiver | TopicSubscriber | MessageConsumer |


ConnectionFactory 與 Destination(受管對象,不建議 new)Connection → 分配通信資源、認證Session → 單線程上下文,事務與確認模式控制MessageProducer / MessageConsumerMessage(Header + Properties + Body)# 下載解壓 ActiveMQ
bin/activemq start
# 訪問 https://localhost:8161/admin (admin/admin) 驗證
// pom.xml 依賴
org.apache.activemq
activemq-client
5.13.2
org.slf4j
slf4j-simple
1.7.19
// jndi.properties
java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory
java.naming.provider.url=tcp://localhost:61616
queue.exampleQueue=example.queue
topic.exampleTopic=example.topic
// SimpleProducer.java (PTP 模式)
Context ctx = new InitialContext();
ConnectionFactory cf = (ConnectionFactory) ctx.lookup("ConnectionFactory");
Destination queue = (Destination) ctx.lookup("exampleQueue");
Connection conn = cf.createConnection();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
for (int i=1; i<=3; i++) {
TextMessage msg = session.createTextMessage("This is the " + i + "th message.");
producer.send(msg);
}
session.close(); conn.close();
// SimpleConsumer.java
Connection conn = cf.createConnection();
conn.start(); // 關鍵:必須 start() 才能接收消息
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
long timeout = 10_000;
for (Message msg = consumer.receive(timeout); msg != null; msg = consumer.receive(timeout)) {
System.out.println("Received: " + ((TextMessage)msg).getText());
}
session.close(); conn.close();
ConnectionFactory cf = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
Destination queue = session.createQueue("example.queue");
Destination topic = session.createTopic("example.topic");