很多初學者誤以為 ActiveMQ 是類似 Spring、Netty 的框架,實際上它更像 Tomcat 這樣的服務器:
# 1. 下載
wget https://apache.freelamp.com/activemq/apache-activemq/5.4.2/apache-activemq-5.4.2-bin.tar.gz
# 2. 解壓
tar xvf apache-activemq-5.4.2-bin.tar.gz
# 3. 啟動
cd apache-activemq-5.4.2/bin
./activemq start
# 4. 驗證:瀏覽器訪問 https://localhost:8161
官網下載穩定版壓縮包,解壓後雙擊 bin/win64/activemq.bat 啟動,同樣通過 https://localhost:8161 訪問管理控制台。
import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;
public class SendMessage {
private static final String BROKER_URL = "tcp://10.20.156.22:61616";
private static final String QUEUE_NAME = "yunpeng.jiangyp";
public void sendMessage() throws JMSException {
// 1. 建立連接工廠
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
// 2. 創建連接並啟動
Connection connection = factory.createConnection();
connection.start();
// 3. 創建會話(非事務、自動確認)
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 4. 目標隊列
Destination destination = session.createQueue(QUEUE_NAME);
// 5. 創建生產者
MessageProducer producer = session.createProducer(destination);
// 6. 構建文本消息
TextMessage message = session.createTextMessage("<hello>world!</hello>");
// 7. 發送
producer.send(message);
// 8. 關閉資源
connection.close();
}
public static void main(String[] args) throws JMSException {
new SendMessage().sendMessage();
}
}
驗證:發送成功後,訪問 https://10.20.156.22:8161/admin/queues.jsp 控制台,可見隊列 yunpeng.jiangyp 消息數增加。
import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;
public class ReceiveMessage {
private static final String BROKER_URL = "tcp://10.20.156.22:61616";
private static final String QUEUE_NAME = "yunpeng.jiangyp";
public static void main(String[] args) throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(QUEUE_NAME);
// 關鍵差異:創建消費者而非生產者
MessageConsumer consumer = session.createConsumer(destination);
while (true) {
// 1秒超時輪詢
Message message = consumer.receive(1000);
if (message == null) break;
if (message instanceof TextMessage) {
TextMessage textMsg = (TextMessage) message;
System.out.println("收到消息: " + textMsg.getText());
}
}
connection.close();
}
}
JMS 定義兩種消息傳遞模型:
| 特性 | Point-to-Point (Queue) | Publish/Subscribe (Topic) |
|---|---|---|
| 消費者數量 | 多個,但每條消息只被一個消費者處理 | 多個,每條消息被所有訂閱者處理 |
| 時間依賴 | 無,消費者隨時可拉取 | 有,訂閱者必須在線才能收到 |
| 典型場景 | 任務分發、負載均衡 | 廣播通知、事件驅動 |
本文示例使用 session.createQueue() 屬於 PTP 模式;若需發布訂閱,改用 session.createTopic() 即可。
MessageListener 接口配合 consumer.setMessageListener(),避免輪詢阻塞DeliveryMode.PERSISTENT 防消息丟失