1、建立pom項目添加pom依賴
<dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-all</artifactId> <version>5.11.2</version> </dependency> |
package com.demo; import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; /** * Created by luwan on 2018/4/14. */ public class App { public static void main(String[] args) throws JMSException { // 發送一個隊列模式的消息 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.223.131:61616"); Connection connection = connectionFactory.createConnection(); connection.start(); // 創建會話 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 消息對象,由於mq是支持很多個業務功能的,每一個業務功能都放在不同的路徑下面 Queue queue = session.createQueue("office-queue"); // 消息內容 TextMessage textMessage = session.createTextMessage("我渴了,來杯水..."); // 發送端 MessageProducer producer = session.createProducer(queue); // 發送消息 producer.send(textMessage); // 關閉連接 producer.close(); session.close(); connection.close(); } } |
4、另一個comsumer接受MQ消息
package macomsumer; import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; /** * Created by luwan on 2018/4/14. */ public class App { public static void main(String[] args) throws Exception { // 創建連接 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.223.131:61616"); Connection connection = connectionFactory.createConnection(); connection.start(); // 創建 會話 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 創建消息對象 Queue queue = session.createQueue("office-queue"); // 接收端 MessageConsumer consumer = session.createConsumer(queue); // 接收消息 consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { // 打印結果 TextMessage textMessage = (TextMessage) message; String text = ""; try { text = textMessage.getText(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.err.println(聽到了" + text + ",積極的響應了要求。。。"); } }); // 等待接收消息 System.in.read(); } } |
4.客戶端表格的字段含義
掛起的消息 在監聽的人數 入隊的消息 消費的消息 |
1 隊列模式的消息,默認永久保存
2 訂閱模式的消息,默認不永久保存,如果需要永久保存,需要爲consumer在服務器上初始化一個永久保存的存儲空間