安裝
官網下載地址:http://activemq.apache.org/
小編這裏以5.9.0版本爲例,做簡單介紹。
下載之後解壓到制定路徑,目錄結構如下:
啓動
直接運行bin下的activemq.bat,出現如下界面。
瀏覽器輸入http://localhost:8161進行訪問,這只是一個安裝成功的頁面。一般用admin訪問,在地址後加/admin,用戶名和密碼都是admin。
如下圖:
實現PTP
JMS有兩種消息模型:PTP和Pub/Sub。這裏以第一種簡單的爲例,來感性的瞭解下。
新建Queue:
代碼實現:
整個過程涉及到消息的生產者(發出消息)、消息的消費者(接收消息)、JMS服務器(負責通信的支持,這裏使用的是activeMQ的支持)。
消息的生產者 Sender
public class Sender {
//消息個數
private static final int SEND_NUMBER = 5;
public static void main(String[] args) {
//初始化開始,包括連接工廠、連接、會話、消息目的、消息生產者
ConnectionFactory connectionFactory;
Connection connection = null;
Session session;
Destination destination;
MessageProducer producer;
//創建連接工廠,使用默認用戶名和密碼。這裏tcp://localhost:61616爲連接地址,當然也可以使用默認地址。
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");
try {
// 構造從工廠得到連接對象
connection = connectionFactory.createConnection();
// 啓動
connection.start();
// 獲取操作連接
session = connection.createSession(Boolean.TRUE,
Session.AUTO_ACKNOWLEDGE);
//創建一個名稱爲TestQueue的消息隊列
destination = session.createQueue("TestQueue");
//得到producer
producer = session.createProducer(destination);
// 設置不持久化
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// 構造消息
sendMessage(session, producer);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
try {
if (null != connection)
connection.close();
} catch (Throwable ignore) {
}
}
}
private static void sendMessage(Session session, MessageProducer producer) throws JMSException {
for (int i = 0; i < SEND_NUMBER; i++) {
TextMessage message=session.createTextMessage("I am a Producer"+i);
System.out.println("發送消息:"+message.getText());
//發送給制定用戶
message.setStringProperty("username", "A");
producer.send(message);
}
}
}
這裏採用的是發送給指定用戶(username=“A”),當然,也可以不加限制,只要在同一消息隊列中的消費者都可以接收。
消息的消費者 Receiver
try {
String clientId = "003";
connection = connectionFactory.createConnection();
// 設置客戶端id
connection.setClientID(clientId);
connection.start();
// 創建會話
session = connection.createSession(Boolean.FALSE,
Session.AUTO_ACKNOWLEDGE);
// 使用同一個消息隊列
destination = session.createQueue("TestQueue");
// consumer=session.createConsumer(destination);
// 指定當前登錄的標識
consumer = session.createConsumer(destination, "username='A'");
while (true) {
// 接收消息
TextMessage message = (TextMessage) consumer.receive(1000000);
if (null != message) {
System.out.println("clientID:" + connection.getClientID()
+ " 收到消息:" + message.getText());
} else {
break;
}
}
} catch (Exception e) {
try {
if (null != connection)
connection.close();
} catch (Throwable ignore) {
}
}
控制檯顯示:
瀏覽器中查看Queue狀態:
在TestQueue隊列中,5個消息入隊,5個消息出隊。