您好,登錄后才能下訂單哦!
ActiveMQ官方下載地址:http://activemq.apache.org/download.html
下載解壓后,執行bin目錄下activemq.bat啟動mq服務
找到lib目錄并引入相關jar包
Sender消息發送者類
package com.ycj.activemq; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; public class Sender { private static final String MQ_USER = "admin"; private static final String MQ_PWD = "admin"; private static final String MQ_URL = "tcp://localhost:61616"; private static final String MQ_QUEUE_DEFAULT = "testQueue"; public static void main(String[] args) throws JMSException { // 創建JMS連接工廠 ConnectionFactory factory = new ActiveMQConnectionFactory(MQ_USER, MQ_PWD, MQ_URL); // 通過工廠獲取鏈接并啟動 Connection connection = factory.createConnection(); connection.start(); // 創建session Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 創建destination 消息目的地 Destination destination = session.createQueue(MQ_QUEUE_DEFAULT); // 根據destination初始化一個生產者 MessageProducer producer = session.createProducer(destination); // 生產者消息不持久化 producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // 生成消息 并發送 Message msg1 = session.createTextMessage("I'm msg1"); Message msg2 = session.createTextMessage("I'm msg2"); producer.send(msg1); producer.send(msg2); session.commit(); connection.close(); System.out.println("producer send msg done!"); } }
Receiver消息接收者類
package com.ycj.activemq; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; public class Receiver { private static final String MQ_USER = "admin"; private static final String MQ_PWD = "admin"; private static final String MQ_URL = "tcp://localhost:61616"; private static final String MQ_QUEUE_DEFAULT = "testQueue"; public static void main(String[] args) throws JMSException { // 創建JMS連接工廠 ConnectionFactory factory = new ActiveMQConnectionFactory(MQ_USER, MQ_PWD, MQ_URL); // 通過工廠獲取鏈接并啟動 Connection connection = factory.createConnection(); connection.start(); // 創建session Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 創建destination 消息目的地 Destination destination = session.createQueue(MQ_QUEUE_DEFAULT); // 根據destination初始化一個消費者 MessageConsumer consumer = session.createConsumer(destination); while (true) { TextMessage msg = (TextMessage) consumer.receive(1000*1000); if (null != msg) { System.out.println("message has been received:" + msg.getText()); } } } }
依次運行Receiver和Sender,控制臺輸出:
Sender
Receiver
打開瀏覽器輸入http://localhost:8161/admin/index.jsp,選擇Queues可以監控隊列消費情況
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。