一、概述與介紹
ActiveMQ 是Apache出品,最流行的、功能強大的即時通訊和集成模式的開源服務器。ActiveMQ 是一個完全支持JMS1.1和J2EE 1.4規范的 JMS Provider實現。提供客戶端支持跨語言和協議,帶有易於在充分支持JMS 1.1和1.4使用J2EE企業集成模式和許多先進的功能。
二、特性
1、 多種語言和協議編寫客戶端。語言: Java、C、C++、C#、Ruby、Perl、Python、PHP。應用協議:OpenWire、Stomp REST、WS Notification、XMPP、AMQP
2、完全支持JMS1.1和J2EE 1.4規范 (持久化,XA消息,事務)
3、對Spring的支持,ActiveMQ可以很容易內嵌到使用Spring的系統裡面去,而且也支持Spring2.0的特性
4、通過了常見J2EE服務器(如 Geronimo、JBoss 4、GlassFish、WebLogic)的測試,其中通過JCA 1.5 resource adaptors的配置,可以讓ActiveMQ可以自動的部署到任何兼容J2EE 1.4 商業服務器上
5、支持多種傳送協議:in-VM、TCP、SSL、NIO、UDP、JGroups、JXTA
6、支持通過JDBC和journal提供高速的消息持久化
7、從設計上保證了高性能的集群,客戶端-服務器,點對點
8、支持Ajax
9、支持與Axis的整合
10、可以很容易得調用內嵌JMS provider,進行測試
三、安裝
開發環境:
System:Windows
JDK:1.6+
IDE:eclipse
apache ActiveMQ 5.8
Email:[email protected]
Blog:http://blog.csdn.net/IBM_hoojo
http://hoojo.cnblogs.com/
1、 下載ActiveMQ,下載地址:http://www.apache.org/dyn/closer.cgi?path=/activemq/apache-activemq/5.8.0/apache-activemq-5.8.0-bin.zip
2、 解壓apache-activemq-5.8.0.zip即可完成ActiveMQ的安裝
3、 解壓後目錄結構如下
+bin (windows下面的bat和unix/linux下面的sh) 啟動ActiveMQ的啟動服務就在這裡
+conf (activeMQ配置目錄,包含最基本的activeMQ配置文件)
+data (默認是空的)
+docs (index,replease版本裡面沒有文檔)
+example (幾個例子)
+lib (activeMQ使用到的lib)
+webapps (系統管理員控制台代碼)
+webapps-demo(系統示例代碼)
-activemq-all-5.8.0.jar (ActiveMQ的binary)
-user-guide.html (部署指引)
-LICENSE.txt
-NOTICE.txt
-README.txt
其他文件就不相信介紹了,搞Java的應該都知道干什麼用的。
你可以進入bin目錄,使用activemq.bat雙擊啟動(windows用戶可以選擇系統位數,如果你是linux的話,就用命令行的發送去啟動),如果一切順利,你就會看見類似下面的信息:
如果你看到這個,那麼恭喜你成功了。如果你啟動看到了異常信息:
Caused by: java.io.IOException: Failed to bind to server socket: tcp://0.0.0.0:61616?maximumConnections=1000&wireformat.maxFrameSize=104857600 due to: java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
那麼我告訴你,很不幸,你的端口被占用了。接下來你大概想知道是哪個程序占用了你的端口,並kill掉該進程或服務。或者你要嘗試修改ActiveMQ的默認端口61616(ActiveMQ使用的默認端口是61616),在大多數情況下,占用61616端口的是Internet Connection Sharing (ICS) 這個Windows服務,你只需停止它就可以啟動ActiveMQ了。
4、 啟動成功就可以訪問管理員界面:http://localhost:8161/admin,默認用戶名和密碼admin/admin。如果你想修改用戶名和密碼的話,在conf/jetty-realm.properties中修改即可。
其中在導航菜單中,Queues是隊列方式消息。Topics是主題方式消息。Subscribers消息訂閱監控查詢。Connections可以查看鏈接數,分別可以查看xmpp、ssl、stomp、openwire、ws和網絡鏈接。Network是網絡鏈接數監控。Send可以發送消息數據。
5、 運行demo示例,在dos控制台輸入activemq.bat xbean:../conf/activemq-demo.xml即可啟動demo示例。官方提供的user-guide.html中的access the web console中是提示輸入:activemq.bat console xbean:conf/activemq-demo.xml,我用這種方式不成功。
當然你還可以用絕對的文件目錄方式:activemq.bat xbean:file:D:/mq/conf/activemq-demo.xml
如果提示conf/activemq-demo.xml沒有找到,你可以嘗試改變下路徑,也就是去掉上面的“..”。通過http://localhost:8161/demo/就可以訪問示例了。
四、消息示例
1、ActiviteMQ消息有3中形式
JMS公共
點對點域
發布/訂閱域
ConnectionFactory
QueueConnectionFactory
TopicConnectionFactory
Connection
QueueConnection
TopicConnection
Destination
Queue
Topic
Session
QueueSession
TopicSession
MessageProducer
QueueSender
TopicPublisher
MessageConsumer
QueueReceiver
TopicSubscriber
(1)、點對點方式(point-to-point)
點對點的消息發送方式主要建立在 Message Queue,Sender,reciever上,Message Queue 存貯消息,Sneder 發送消息,receive接收消息.具體點就是Sender Client發送Message Queue ,而 receiver Cliernt從Queue中接收消息和"發送消息已接受"到Quere,確認消息接收。消息發送客戶端與接收客戶端沒有時間上的依賴,發送客戶端可以在任何時刻發送信息到Queue,而不需要知道接收客戶端是不是在運行
(2)、發布/訂閱 方式(publish/subscriber Messaging)
發布/訂閱方式用於多接收客戶端的方式.作為發布訂閱的方式,可能存在多個接收客戶端,並且接收端客戶端與發送客戶端存在時間上的依賴。一個接收端只能接收他創建以後發送客戶端發送的信息。作為subscriber ,在接收消息時有兩種方法,destination的receive方法,和實現message listener 接口的onMessage 方法。
2、ActiviteMQ接收和發送消息基本流程
發送消息的基本步驟:
(1)、創建連接使用的工廠類JMS ConnectionFactory
(2)、使用管理對象JMS ConnectionFactory建立連接Connection,並啟動
(3)、使用連接Connection 建立會話Session
(4)、使用會話Session和管理對象Destination創建消息生產者MessageSender
(5)、使用消息生產者MessageSender發送消息
消息接收者從JMS接受消息的步驟
(1)、創建連接使用的工廠類JMS ConnectionFactory
(2)、使用管理對象JMS ConnectionFactory建立連接Connection,並啟動
(3)、使用連接Connection 建立會話Session
(4)、使用會話Session和管理對象Destination創建消息接收者MessageReceiver
(5)、使用消息接收者MessageReceiver接受消息,需要用setMessageListener將MessageListener接口綁定到MessageReceiver消息接收者必須實現了MessageListener接口,需要定義onMessage事件方法。
五、代碼示例
在代碼開始,我們先建一個project,在這個project中添加如下jar包
添加完jar包後就可以開始實際的代碼工作了。
1、 使用JMS方式發送接收消息
消息發送者
package com.hoo.mq.jms;import javax.jms.Connection;import javax.jms.ConnectionFactory;import javax.jms.DeliveryMode;import javax.jms.Destination;import javax.jms.MessageProducer;import javax.jms.Session;import javax.jms.TextMessage;import org.apache.activemq.ActiveMQConnection;import org.apache.activemq.ActiveMQConnectionFactory;/*** function: 消息發送者* @author hoojo* @createDate 2013-6-19 上午11:26:43* @file MessageSender.java* @package com.hoo.mq.jms* @project ActiveMQ-5.8* @blog http://blog.csdn.net/IBM_hoojo* @email [email protected]* @version 1.0*/public class MessageSender {// 發送次數public static final int SEND_NUM = 5;// tcp 地址public static final String BROKER_URL = "tcp://localhost:61616";// 目標,在ActiveMQ管理員控制台創建 http://localhost:8161/admin/queues.jsppublic static final String DESTINATION = "hoo.mq.queue";/*** function: 發送消息* @author hoojo* @createDate 2013-6-19 下午12:05:42* @param session* @param producer* @throws Exception*/public static void sendMessage(Session session, MessageProducer producer) throws Exception {for (int i = 0; i < SEND_NUM; i++) {String message = "發送消息第" + (i + 1) + "條";TextMessage text = session.createTextMessage(message);System.out.println(message);producer.send(text);}}public static void run() throws Exception {Connection connection = null;Session session = null;try {// 創建鏈接工廠ConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);// 通過工廠創建一個連接connection = factory.createConnection();// 啟動連接connection.start();// 創建一個session會話session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);// 創建一個消息隊列Destination destination = session.createQueue(DESTINATION);// 創建消息制作者MessageProducer producer = session.createProducer(destination);// 設置持久化模式producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);sendMessage(session, producer);// 提交會話session.commit();} catch (Exception e) {throw e;} finally {// 關閉釋放資源if (session != null) {session.close();}if (connection != null) {connection.close();}}}public static void main(String[] args) throws Exception {MessageSender.run();}}接受者
package com.hoo.mq.jms;import javax.jms.Connection;import javax.jms.ConnectionFactory;import javax.jms.Destination;import javax.jms.Message;import javax.jms.MessageConsumer;import javax.jms.Session;import javax.jms.TextMessage;import org.apache.activemq.ActiveMQConnection;import org.apache.activemq.ActiveMQConnectionFactory;/*** function: 消息接收者* @author hoojo* @createDate 2013-6-19 下午01:34:27* @file MessageReceiver.java* @package com.hoo.mq.jms* @project ActiveMQ-5.8* @blog http://blog.csdn.net/IBM_hoojo* @email [email protected]* @version 1.0*/public class MessageReceiver {// tcp 地址public static final String BROKER_URL = "tcp://localhost:61616";// 目標,在ActiveMQ管理員控制台創建 http://localhost:8161/admin/queues.jsppublic static final String DESTINATION = "hoo.mq.queue";public static void run() throws Exception {Connection connection = null;Session session = null;try {// 創建鏈接工廠ConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);// 通過工廠創建一個連接connection = factory.createConnection();// 啟動連接connection.start();// 創建一個session會話session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);// 創建一個消息隊列Destination destination = session.createQueue(DESTINATION);// 創建消息制作者MessageConsumer consumer = session.createConsumer(destination);while (true) {// 接收數據的時間(等待) 100 msMessage message = consumer.receive(1000 * 100);TextMessage text = (TextMessage) message;if (text != null) {System.out.println("接收:" + text.getText());} else {break;}}// 提交會話session.commit();} catch (Exception e) {throw e;} finally {// 關閉釋放資源if (session != null) {session.close();}if (connection != null) {connection.close();}}}public static void main(String[] args) throws Exception {MessageReceiver.run();}}
2、 Queue隊列方式發送點對點消息數據
發送方
package com.hoo.mq.queue;import javax.jms.DeliveryMode;import javax.jms.MapMessage;import javax.jms.Queue;import javax.jms.QueueConnection;import javax.jms.QueueConnectionFactory;import javax.jms.QueueSession;import javax.jms.Session;import org.apache.activemq.ActiveMQConnection;import org.apache.activemq.ActiveMQConnectionFactory;/*** function: Queue 方式消息發送者* @author hoojo* @createDate 2013-6-19 下午04:34:36* @file QueueSender.java* @package com.hoo.mq.queue* @project ActiveMQ-5.8* @blog http://blog.csdn.net/IBM_hoojo* @email [email protected]* @version 1.0*/public class QueueSender {// 發送次數public static final int SEND_NUM = 5;// tcp 地址public static final String BROKER_URL = "tcp://localhost:61616";// 目標,在ActiveMQ管理員控制台創建 http://localhost:8161/admin/queues.jsppublic static final String DESTINATION = "hoo.mq.queue";/*** function: 發送消息* @author hoojo* @createDate 2013-6-19 下午12:05:42* @param session* @param sender* @throws Exception*/public static void sendMessage(QueueSession session, javax.jms.QueueSender sender) throws Exception {for (int i = 0; i < SEND_NUM; i++) {String message = "發送消息第" + (i + 1) + "條";MapMessage map = session.createMapMessage();map.setString("text", message);map.setLong("time", System.currentTimeMillis());System.out.println(map);sender.send(map);}}public static void run() throws Exception {QueueConnection connection = null;QueueSession session = null;try {// 創建鏈接工廠QueueConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);// 通過工廠創建一個連接connection = factory.createQueueConnection();// 啟動連接connection.start();// 創建一個session會話session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);// 創建一個消息隊列Queue queue = session.createQueue(DESTINATION);// 創建消息發送者javax.jms.QueueSender sender = session.createSender(queue);// 設置持久化模式sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);sendMessage(session, sender);// 提交會話session.commit();} catch (Exception e) {throw e;} finally {// 關閉釋放資源if (session != null) {session.close();}if (connection != null) {connection.close();}}}public static void main(String[] args) throws Exception {QueueSender.run();}}接收方
package com.hoo.mq.queue;import javax.jms.JMSException;import javax.jms.MapMessage;import javax.jms.Message;import javax.jms.MessageListener;import javax.jms.Queue;import javax.jms.QueueConnection;import javax.jms.QueueConnectionFactory;import javax.jms.QueueSession;import javax.jms.Session;import org.apache.activemq.ActiveMQConnection;import org.apache.activemq.ActiveMQConnectionFactory;/*** function: 消息接收者; 依賴hawtbuf-1.9.jar* @author hoojo* @createDate 2013-6-19 下午01:34:27* @file MessageReceiver.java* @package com.hoo.mq.queue* @project ActiveMQ-5.8* @blog http://blog.csdn.net/IBM_hoojo* @email [email protected]* @version 1.0*/public class QueueReceiver {// tcp 地址public static final String BROKER_URL = "tcp://localhost:61616";// 目標,在ActiveMQ管理員控制台創建 http://localhost:8161/admin/queues.jsppublic static final String TARGET = "hoo.mq.queue";public static void run() throws Exception {QueueConnection connection = null;QueueSession session = null;try {// 創建鏈接工廠QueueConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);// 通過工廠創建一個連接connection = factory.createQueueConnection();// 啟動連接connection.start();// 創建一個session會話session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);// 創建一個消息隊列Queue queue = session.createQueue(TARGET);// 創建消息制作者javax.jms.QueueReceiver receiver = session.createReceiver(queue);receiver.setMessageListener(new MessageListener() {public void onMessage(Message msg) {if (msg != null) {MapMessage map = (MapMessage) msg;try {System.out.println(map.getLong("time") + "接收#" + map.getString("text"));} catch (JMSException e) {e.printStackTrace();}}}});// 休眠100ms再關閉Thread.sleep(1000 * 100);// 提交會話session.commit();} catch (Exception e) {throw e;} finally {// 關閉釋放資源if (session != null) {session.close();}if (connection != null) {connection.close();}}}public static void main(String[] args) throws Exception {QueueReceiver.run();}}
3、 Topic主題發布和訂閱消息
消息發送方
package com.hoo.mq.topic;import javax.jms.DeliveryMode;import javax.jms.MapMessage;import javax.jms.Session;import javax.jms.Topic;import javax.jms.TopicConnection;import javax.jms.TopicConnectionFactory;import javax.jms.TopicPublisher;import javax.jms.TopicSession;import org.apache.activemq.ActiveMQConnection;import org.apache.activemq.ActiveMQConnectionFactory;/*** function: Queue 方式消息發送者* @author hoojo* @createDate 2013-6-19 下午04:34:36* @file QueueSender.java* @package com.hoo.mq.topic* @project ActiveMQ-5.8* @blog http://blog.csdn.net/IBM_hoojo* @email [email protected]* @version 1.0*/public class TopicSender {// 發送次數public static final int SEND_NUM = 5;// tcp 地址public static final String BROKER_URL = "tcp://localhost:61616";// 目標,在ActiveMQ管理員控制台創建 http://localhost:8161/admin/queues.jsppublic static final String DESTINATION = "hoo.mq.topic";/*** function: 發送消息* @author hoojo* @createDate 2013-6-19 下午12:05:42* @param session 會話* @param publisher 發布者* @throws Exception*/public static void sendMessage(TopicSession session, TopicPublisher publisher) throws Exception {for (int i = 0; i < SEND_NUM; i++) {String message = "發送消息第" + (i + 1) + "條";MapMessage map = session.createMapMessage();map.setString("text", message);map.setLong("time", System.currentTimeMillis());System.out.println(map);publisher.send(map);}}public static void run() throws Exception {TopicConnection connection = null;TopicSession session = null;try {// 創建鏈接工廠TopicConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);// 通過工廠創建一個連接connection = factory.createTopicConnection();// 啟動連接connection.start();// 創建一個session會話session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);// 創建一個消息隊列Topic topic = session.createTopic(DESTINATION);// 創建消息發送者TopicPublisher publisher = session.createPublisher(topic);// 設置持久化模式publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);sendMessage(session, publisher);// 提交會話session.commit();} catch (Exception e) {throw e;} finally {// 關閉釋放資源if (session != null) {session.close();}if (connection != null) {connection.close();}}}public static void main(String[] args) throws Exception {TopicSender.run();}}接收方
package com.hoo.mq.topic;import javax.jms.JMSException;import javax.jms.MapMessage;import javax.jms.Message;import javax.jms.MessageListener;import javax.jms.Session;import javax.jms.Topic;import javax.jms.TopicConnection;import javax.jms.TopicConnectionFactory;import javax.jms.TopicSession;import javax.jms.TopicSubscriber;import org.apache.activemq.ActiveMQConnection;import org.apache.activemq.ActiveMQConnectionFactory;/*** function: 消息接收者; 依賴hawtbuf-1.9.jar* @author hoojo* @createDate 2013-6-19 下午01:34:27* @file MessageReceiver.java* @package com.hoo.mq.topic* @project ActiveMQ-5.8* @blog http://blog.csdn.net/IBM_hoojo* @email [email protected]* @version 1.0*/public class TopicReceiver {// tcp 地址public static final String BROKER_URL = "tcp://localhost:61616";// 目標,在ActiveMQ管理員控制台創建 http://localhost:8161/admin/queues.jsppublic static final String TARGET = "hoo.mq.topic";public static void run() throws Exception {TopicConnection connection = null;TopicSession session = null;try {// 創建鏈接工廠TopicConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);// 通過工廠創建一個連接connection = factory.createTopicConnection();// 啟動連接connection.start();// 創建一個session會話session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);// 創建一個消息隊列Topic topic = session.createTopic(TARGET);// 創建消息制作者TopicSubscriber subscriber = session.createSubscriber(topic);subscriber.setMessageListener(new MessageListener() {public void onMessage(Message msg) {if (msg != null) {MapMessage map = (MapMessage) msg;try {System.out.println(map.getLong("time") + "接收#" + map.getString("text"));} catch (JMSException e) {e.printStackTrace();}}}});// 休眠100ms再關閉Thread.sleep(1000 * 100);// 提交會話session.commit();} catch (Exception e) {throw e;} finally {// 關閉釋放資源if (session != null) {session.close();}if (connection != null) {connection.close();}}}public static void main(String[] args) throws Exception {TopicReceiver.run();}}
4、 整合Spring實現消息發送和接收,在整合之前我們需要添加jar包,需要的jar包如下
這些jar包可以在D:\apache-activemq-5.8.0\lib這個lib目錄中找到,添加完jar包後就開始編碼工作。
消息發送者
package com.hoo.mq.spring.support;import java.util.Date;import javax.jms.JMSException;import javax.jms.MapMessage;import javax.jms.Message;import javax.jms.Session;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import org.springframework.jms.core.JmsTemplate;import org.springframework.jms.core.MessageCreator;/*** function: Spring JMSTemplate 消息發送者* @author hoojo* @createDate 2013-6-24 下午02:18:48* @file Sender.java* @package com.hoo.mq.spring.support* @project ActiveMQ-5.8* @blog http://blog.csdn.net/IBM_hoojo* @email [email protected]* @version 1.0*/public class Sender {public static void main(String[] args) {ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext-*.xml");JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");jmsTemplate.send(new MessageCreator() {public Message createMessage(Session session) throws JMSException {MapMessage message = session.createMapMessage();message.setString("message", "current system time: " + new Date().getTime());return message;}});}}消息接收者
package com.hoo.mq.spring.support;import java.util.Map;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import org.springframework.jms.core.JmsTemplate;/*** function: Spring JMSTemplate 消息接收者* @author hoojo* @createDate 2013-6-24 下午02:22:32* @file Receiver.java* @package com.hoo.mq.spring.support* @project ActiveMQ-5.8* @blog http://blog.csdn.net/IBM_hoojo* @email [email protected]* @version 1.0*/public class Receiver {@SuppressWarnings("unchecked")public static void main(String[] args) {ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext-*.xml");JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");while(true) {Mapmap = (Map ) jmsTemplate.receiveAndConvert(); System.out.println("收到消息:" + map.get("message"));}}}這裡主要是用到了JmsTemplate這個消息模板,這個對象在spring的IoC容器中管理,所以要從spring的容器上下文中獲取。下面看看spring的配置文件applicationContext-beans.xml內容:
xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd">這裡的整合就比較簡單了,如果你是web工程,那你在需要用jms的時候,只需用注入jmsTemplate即可。