深刻浅出 消息队列 ActiveMQ------加强版

  本小节咱们将讲解Apache开源下的ActiveMQ,而ActiveMQ是JMS的一个具体实现。JMS即Java消息服务(Java Message Service)应用程序接口是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送消息,进行异步通讯。Java消息服务是一个与具体平台无关的API,绝大多数MOM提供商都对JMS提供支持。html

     在学习ActiveMQ以前,咱们有必要对JMS进行一下简单的了解,因为篇幅的限制,对于JMS的学习请参考下面的连接:java

     JMS参考连接点击这里linux

1、 概述与介绍web

ActiveMQ 是Apache出品,最流行的、功能强大的即时通信和集成模式的开源服务器。ActiveMQ 是一个彻底支持JMS1.1和J2EE 1.4规范的 JMS Provider实现。提供客户端支持跨语言和协议,带有易于在充分支持JMS 1.1和1.4使用J2EE企业集成模式和许多先进的功能。spring

 

2、 特性apache

一、 多种语言和协议编写客户端。语言: Java、C、C++、C#、Ruby、Perl、Python、PHP。应用协议:OpenWire、Stomp REST、WS Notification、XMPP、AMQPwindows

二、彻底支持JMS1.1和J2EE 1.4规范 (持久化,XA消息,事务)服务器

三、对Spring的支持,ActiveMQ能够很容易内嵌到使用Spring的系统里面去,并且也支持Spring2.0的特性网络

四、经过了常见J2EE服务器(如 Geronimo、JBoss 四、GlassFish、WebLogic)的测试,其中经过JCA 1.5 resource adaptors的配置,可让ActiveMQ能够自动的部署到任何兼容J2EE 1.4 商业服务器上session

五、支持多种传送协议:in-VM、TCP、SSL、NIO、UDP、JGroups、JXTA

六、支持经过JDBC和journal提供高速的消息持久化

七、从设计上保证了高性能的集群,客户端-服务器,点对点

八、支持Ajax

九、支持与Axis的整合

十、能够很容易得调用内嵌JMS provider,进行测试

对于Active MQ更多的信息能够点击这里

3、 安装

开发环境:

System:Windows

JDK:1.6+

IDE:myeclipse

apache ActiveMQ 5.8

Email:1261245595@qq.com

Blog:http://www.cnblogs.com/xiohao

 

一、 下载ActiveMQ,下载地址:http://www.apache.org/dyn/closer.cgi?path=/activemq/apache-activemq/5.8.0/apache-activemq-5.8.0-bin.zip

二、 解压apache-activemq-5.8.0.zip便可完成ActiveMQ的安装

三、 解压后目录结构以下

image

+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的话,就用命令行的发送去启动),若是一切顺利,你就会看见相似下面的信息:

image

若是你看到这个,那么恭喜你成功了。若是你启动看到了异常信息:

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了。

四、 启动成功就能够访问管理员界面:http://localhost:8161/admin,默认用户名和密码admin/admin。若是你想修改用户名和密码的话,在conf/jetty-realm.properties中修改便可。

image

其中在导航菜单中,Queues是队列方式消息。Topics是主题方式消息。Subscribers消息订阅监控查询。Connections能够查看连接数,分别能够查看xmpp、ssl、stomp、openwire、ws和网络连接。Network是网络连接数监控。Send能够发送消息数据。

五、 运行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

image

若是提示conf/activemq-demo.xml没有找到,你能够尝试改变下路径,也就是去掉上面的“..”。经过http://localhost:8161/demo/ 就能够访问示例了。

image

 

4、 消息示例

一、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 方法。

二、ActiviteMQ接收和发送消息基本流程

image

发送消息的基本步骤:

(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事件方法。

5、 代码示例

在代码开始,咱们先建一个project,在这个project中添加以下jar包

image

添加完jar包后就能够开始实际的代码工做了。

但对于我我的而言,其实不必费劲巴拉的加入这三个包,你能够直接加入下面红色圈出来的jar,包含了mq开发的全部jar文件,方便快捷。

 

 

ActiviteMQ消息有3中形式,

一、JMS公共 

二、点对点域

三、发布/订阅域

它们的前半部分基本上差很少,建立链接工厂,获取相应的链接,获取相应的session,主要的区别在于

一、JMS公共  使用MessageProducer发送消息

二、点对点域  使用QueueSender发送消息

三、发布/订阅域 使用TopicPublisher发送消息

若是你查看QueueSender和TopicPublisher的源码,你会发现,它们都是MessageProducer接口的子接口,其它你懂的~

 

一、 使用JMS方式发送接收消息

消息发送者,消息的发送者

 

 
  
package com.xx.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;
	 
	/**
	 *  消息发送者
	 * @author hao
	 * @since    2015-9-24
	 * @file MessageSender.java
	 * @package com.xx.mq.jms
	 * @project ActiveMQ-5.8
	 * @blog http://cnblogs.com/xiohao
	 * @email 1261245595@qq.com
	 * @version 1.0
	 */
	public class MessageSender {
	 
	    // 发送次数
	    public static final int SEND_NUM = 10;
	    // tcp 地址 服务器器端地址
	    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
	    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/.jsp中能够查询到发送的mq消息
	    public static final String DESTINATION = "mq.jms";
	    //测试链接使用默认的用户名
	    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
	    //测试链接使用默认的密码
	    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
        /**
         * 发送消息
         * @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);
	        }
	        //生产者睡眠100s
//	        Thread.sleep(100000);
	    }
	    
	    public static void run() throws Exception {
	        
	        Connection connection = null;
	        Session session = null;
	        try {
	            // 一、建立连接工厂
	            ConnectionFactory factory = new ActiveMQConnectionFactory(MessageReceiver_Listener.DEFAULT_USER, MessageReceiver_Listener.DEFAULT_PASSWORD, MessageReceiver_Listener.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();
	    }
	}
 
  

 

 
 

 

消息的接收者——————使用Receive的接收方式,在实际的开发中使用比较少。

 

 
  
package com.xx.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;
 
/**
 *  消息发送者
 * @author hao
 * @since    2015-9-24
 * @file MessageReceiver.java
 * @package com.xx.mq.jms
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class MessageReceiver_Receive {
 
    // 发送次数
    public static final int SEND_NUM = 10;
    // tcp 地址 服务器器端地址
    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/queues.jsp中能够查询到发送的mq消息
    public static final String DESTINATION = "mq.jms";
    //测试链接使用默认的用户名
    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
    //测试链接使用默认的密码
    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
    
    
    public static void run() throws Exception {
        
        Connection connection = null;
        Session session = null;
        try {
            // 建立连接工厂
            ConnectionFactory factory = new ActiveMQConnectionFactory(MessageReceiver_Receive.DEFAULT_USER, MessageReceiver_Receive.DEFAULT_PASSWORD, MessageReceiver_Receive.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) {
                // 接收数据的时间(等待) 10 s ,超过10秒自动超时
                Message message = consumer.receive(1000*10);
                // 接收相关的消息
                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_Receive.run();
    }
}

消息的接收者——————使用Listener的接收方式,在实际的开发中使用比较多。

package com.xx.mq.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
 
/**
 *  消息发送者
 * @author hao
 * @since    2015-9-24
 * @file MessageReceiver.java
 * @package com.xx.mq.jms
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class MessageReceiver_Listener {
 
    // 发送次数
    public static final int SEND_NUM = 10;
    // tcp 地址 服务器器端地址
    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/queues.jsp中能够查询到发送的mq消息
    public static final String DESTINATION = "mq.jms";
    //测试链接使用默认的用户名
    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
    //测试链接使用默认的密码
    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
    
    
    public static void run() throws Exception {
        
        Connection connection = null;
        Session session = null;
        try {
            // 一、建立连接工厂
            ConnectionFactory factory = new ActiveMQConnectionFactory(MessageReceiver_Listener.DEFAULT_USER, MessageReceiver_Listener.DEFAULT_PASSWORD, MessageReceiver_Listener.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);
            
            consumer.setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message msg) {
		             // 接收相关的消息
		             TextMessage text = (TextMessage) msg;
		             if (text != null) {
		                  try {
							System.out.println("接收:" + text.getText());
						} catch (JMSException e) {
							e.printStackTrace();
						}
		             }
				}
            });
            
          //让当前主线程睡眠10秒,单可是监听器会继续执行 
          Thread.sleep(1000*10);
 
        } 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_Listener.run();
    }
}
 
  

 

 
  

 运行结果展现:

一、点击运行MessageSender的主方法,查看服务器控制台下面的 http://localhost:8161/admin/queues.jsp

     能够看到下面的结果:

    

二、运行MessageReceiver_Listener或者MessageReceiver_Receive的main方法,便可在控制台看到下面的结果,表示消费者消费成功。

 

 

 
 

 

二、 Queue队列方式发送点对点消息数据

发送方,对于这种点对点的发送方式而言,一旦服务器中的消息被相应的消费者消费后,对应的消息就会马上被移出消息队列。

 

 
  
package com.xx.mq.queue;

import javax.jms.DeliveryMode;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
 
/**
 *  点对点消息发送者
 * @author hao
 * @since    2015-9-24
 * @file QueueSender.java
 * @package com.xx.mq.queue
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class QueueSender {
    
    // 发送次数
    public static final int SEND_NUM = 10;
    // tcp 地址 服务器器端地址
    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/queues.jsp中能够查询到发送的mq消息
    public static final String DESTINATION = "mq.queue";
    //测试链接使用默认的用户名
    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
    //测试链接使用默认的密码
    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
    
   /**
    * 发送消息  
    * @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) + "条消息";
        	TextMessage textMessage = session.createTextMessage(message);
            System.out.println(textMessage.getText());
            sender.send(textMessage);
        }
    }
    
    /**
     * 建立链接并发送消息
     * @throws Exception
     */
    public static void run() throws Exception {
        
        //点对点队列链接
        QueueConnection connection = null;
        //点对点会话Session
        QueueSession session = null;
        try {
            // 一、建立连接工厂
            QueueConnectionFactory factory = new ActiveMQConnectionFactory(QueueSender.DEFAULT_USER, QueueSender.DEFAULT_PASSWORD, QueueSender.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();
    }
}

 

 

 

接收方——————使用Receive的方式接收相关的消息,在实际开发中使用的比较少。

 

 
  
package com.xx.mq.queue;

import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
 
/**
 *  点对点消息接收者  直接Receive 方式
 * @author hao
 * @since    2015-9-24
 * @file QueueReceiver_Receive.java
 * @package com.xx.mq.queue
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class QueueReceiver_Receive {
 
	 // 接收消息的个数
    public static final int Receive_NUM = 10;
    // tcp 地址 服务器器端地址
    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/queues.jsp中能够查询到发送的mq消息
    public static final String DESTINATION = "mq.queue";
    //测试链接使用默认的用户名
    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
    //测试链接使用默认的密码
    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
    
    public static void run() throws Exception {
        
        QueueConnection connection = null;
        QueueSession session = null;
        try {
            // 一、建立连接工厂
            QueueConnectionFactory factory = new ActiveMQConnectionFactory(QueueReceiver_Receive.DEFAULT_USER, QueueReceiver_Receive.DEFAULT_PASSWORD,QueueReceiver_Receive.BROKER_URL);
            // 二、经过工厂建立一个链接
            connection = factory.createQueueConnection();
            // 三、启动链接
            connection.start();
            // 四、建立一个session会话
            session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 五、建立一个消息队列
            Queue queue = session.createQueue(DESTINATION);
            // 建立消息接收者
            javax.jms.QueueReceiver receiver = session.createReceiver(queue);
            // 直接Receive 方式 接收消息  
            for(int i=0;i<QueueReceiver_Receive.Receive_NUM;i++){
            	TextMessage textMessage=(TextMessage) receiver.receive();
            	if(textMessage!=null)
            	System.out.println("接收#" + textMessage.getText());
            }
            // 提交会话
            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_Receive.run();
    }
}
 
  

 接收方——————使用Listener监听者的方式接收相关的消息,在实际开发中使用比较多。

 
  
package com.xx.mq.queue;

import javax.jms.JMSException;
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 javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
 
/**
 *  点对点消息接收者 使用Listener 监听方式 在实际项目开发中使用比较多
 * @author hao
 * @since    2015-9-24
 * @file QueueReceiver_Listener.java
 * @package com.xx.mq.queue
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class QueueReceiver_Listener {
 
    // tcp 地址 服务器器端地址
    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/queues.jsp中能够查询到发送的mq消息
    public static final String DESTINATION = "mq.queue";
    //测试链接使用默认的用户名
    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
    //测试链接使用默认的密码
    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
    
    public static void run() throws Exception {
        
        QueueConnection connection = null;
        QueueSession session = null;
        try {
            // 一、建立连接工厂
            QueueConnectionFactory factory = new ActiveMQConnectionFactory(QueueReceiver_Listener.DEFAULT_USER, QueueReceiver_Listener.DEFAULT_PASSWORD,QueueReceiver_Listener.BROKER_URL);
            // 二、经过工厂建立一个链接
            connection = factory.createQueueConnection();
            // 三、启动链接
            connection.start();
            // 四、建立一个session会话
            session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 五、建立一个消息队列
            Queue queue = session.createQueue(DESTINATION);
            // 建立消息接收者
            javax.jms.QueueReceiver receiver = session.createReceiver(queue);
            
            //使用内部类为消息接收者加载相应的Listener监听
            receiver.setMessageListener(new MessageListener() { 
            	//重写onMessage方法
                public void onMessage(Message msg) { 
                    if (msg != null) {
                        TextMessage textMessage = (TextMessage) msg;
                        try {
                            System.out.println("接收#" + textMessage.getText());
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                } 
            }); 
            // 休眠10s再关闭 接收生产者发送的所有的10条消息
            // 须要注意的是这里使用sleep会使当前正在执行的线程进入休眠状态
            // 也就是QueueReceiver_Listener这个类进入休眠状态了,而接收者的监听器仍然会继续执行的哦。
            Thread.sleep(1000 * 10); 
            
            // 提交会话
            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_Listener.run();
    }
}
 
  

 运行结果展现:

一、点击运行QueueSender的主方法,查看服务器控制台下面的 http://localhost:8161/admin/queues.jsp

     能够看到下面的结果:

  

二、运行QueueReceiver_Listener或者QueueReceiver_Receive的main方法,便可在控制台看到下面的结果,表示消费者消费成功。

 

 
 

 

 

三、 Topic主题发布和订阅消息

消息发送方:

 

 
  
package com.xx.mq.topic;
 
import javax.jms.DeliveryMode;
import javax.jms.Session;
import javax.jms.TextMessage;
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;
 
 
/**
 *  发布订阅式消息发送者
 * @author hao
 * @since    2015-9-24
 * @file TopicProducer.java
 * @package com.xx.mq.topic
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class TopicProducer {
    
	 // 发送次数
    public static final int SEND_NUM = 10;
    // tcp 地址 服务器器端地址
    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/topics.jsp中能够查询到发送的mq消息
    public static final String DESTINATION = "mq.topic";
    //测试链接使用默认的用户名
    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
    //测试链接使用默认的密码
    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
 
    /**
     * 消息发送端
     * @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) + "条";
            
            TextMessage textMessage = session.createTextMessage(message);
            System.out.println(textMessage.getText());
            //发送 Topic消息
            publisher.send(textMessage);
        }
    }
    
    public  void run() throws Exception {
        //Topic链接
        TopicConnection connection = null;
        //Topic会话
        TopicSession session = null;
        try {
            // 一、建立连接工厂
            TopicConnectionFactory factory = new ActiveMQConnectionFactory(TopicProducer.DEFAULT_USER, TopicProducer.DEFAULT_PASSWORD, TopicProducer.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 {
      new  TopicProducer().run();
    }
}
 
  

 

 
 

 

接收方——————使用Receive的方式对消息进行接收,在实际开发中使用的比较少。

 

 
  
package com.xx.mq.topic;
 
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
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;
 
/**
 *  发布订阅式消息接收者
 * @author hao
 * @since    2015-9-24
 * @file TopicReceiver_Receive.java
 * @package com.xx.mq.topic
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class TopicReceiver_Receive {
 

    // tcp 地址 服务器器端地址
    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/topics.jsp中能够查询到发送的mq消息
    public static final String DESTINATION = "mq.topic";
    //测试链接使用默认的用户名
    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
    //测试链接使用默认的密码
    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
 
    
    public static void run() throws Exception {
        
        TopicConnection connection = null;
        TopicSession session = null;
        try {
            // 一、建立连接工厂
            TopicConnectionFactory factory = new ActiveMQConnectionFactory(TopicReceiver_Receive.DEFAULT_USER, TopicReceiver_Receive.DEFAULT_PASSWORD, TopicReceiver_Receive.BROKER_URL);
            // 二、经过工厂建立一个链接
            connection = factory.createTopicConnection();
            // 三、启动链接
            connection.start();
            // 四、建立一个session会话
            session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 五、建立一个消息队列
            Topic topic = session.createTopic(DESTINATION);
            // 六、建立消息制做者
            final TopicSubscriber subscriber = session.createSubscriber(topic);
            
            //接收Topic生产者发送过来的消息
            //须要注意的是此处须要启动一个新的线程来处理问题
            new Thread(){
            	public void run(){
              	TextMessage textMessage = null;
				try {
					while(true){//持续接收消息
					textMessage = (TextMessage) subscriber.receive();
					if(textMessage==null)
					 break;
					System.out.println("接收#" + textMessage.getText());
					}
				} catch (JMSException e) {
					e.printStackTrace();
				}
            	}
            }.start();
            
            // 休眠100s再关闭 接收生产者发送的所有的10条消息
            // 须要注意的是这里使用sleep会使当前正在执行的线程进入休眠状态
            // 也就是TopicReceiver_Receive这个类进入休眠状态了,而接收者.start方法刚刚启动的新线程会继续执行的哦。
            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_Receive.run();
    }
}
 
  

 接收方——————使用的方式Listener监听器的对消息进行接收,在实际开发中使用的比较多。

 

package com.xx.mq.topic;
 
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
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;
 
/**
 *  发布订阅式消息接收者
 * @author hao
 * @since    2015-9-24
 * @file TopicReceiver_Listener.java
 * @package com.xx.mq.topic
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class TopicReceiver_Listener {
 

    // tcp 地址 服务器器端地址
    public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL;  // 其值为 "tcp://localhost:61616";
    // 目标地址,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/topics.jsp中能够查询到发送的mq消息
    public static final String DESTINATION = "mq.topic";
    //测试链接使用默认的用户名
    public static final String DEFAULT_USER = ActiveMQConnection.DEFAULT_USER;//默认为null
    //测试链接使用默认的密码
    public static final String DEFAULT_PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认为null
 
    
    public static void run() throws Exception {
        
        TopicConnection connection = null;
        TopicSession session = null;
        try {
            // 一、建立连接工厂
            TopicConnectionFactory factory = new ActiveMQConnectionFactory(TopicReceiver_Listener.DEFAULT_USER, TopicReceiver_Listener.DEFAULT_PASSWORD, TopicReceiver_Listener.BROKER_URL);
            // 二、经过工厂建立一个链接
            connection = factory.createTopicConnection();
            // 三、启动链接
            connection.start();
            // 四、建立一个session会话
            session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 五、建立一个消息队列
            Topic topic = session.createTopic(DESTINATION);
            // 六、建立消息制做者
            TopicSubscriber subscriber = session.createSubscriber(topic);
            
            //使用监听器的方式订阅消息
            subscriber.setMessageListener(new MessageListener() { 
                public void onMessage(Message msg) { 
                    if (msg != null) {
                        TextMessage textMessage = (TextMessage) msg;
                        try {
                            System.out.println("接收#" + textMessage.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } 
            }); 
            // 休眠100s再关闭 接收生产者发送的所有的10条消息
            // 须要注意的是这里使用sleep会使当前正在执行的线程进入休眠状态
            // 也就是TopicReceiver_Listener这个类进入休眠状态了,而接收者的监听器仍然会继续执行的哦。
            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_Listener.run();
    }
}

 

 

 

运行结果展现:
一、首先启动消费者,须要注意的是发布订阅式的消息模式同点对点消费的模式不一样。

对于点对点的通讯模式而言,咱们须要首先启动生产者,将消息发送到服务器上的消息队列上面,最后启动生产者,进行消息的消费操做。
对于发布订阅式的通讯模式而言,消费者必须先于生产者而启动,否者的话,消费者是接收不到相应的消费消息的。
相应的访问链接为:  http://localhost:8161/admin/topics.jsp
启动消费者后(这里咱们分别启动Receive和Listener两个消费者,模拟一个主题多个消费者的状况,代码中咱们设置消费者hold的时间为100s,超时后消费者将自动关闭,若是您的反射弧太长
建议设置为更大值,ps开个玩笑。),咱们能够在服务器上看到下面的内容:
一、首先启动生产者,一旦生成这启动以后,咱们将会在控制台看到消息的消费状况。


经过这个控制台,咱们清楚的看到同一个主题被两个消费者消费了。须要注意的是启动生产者后,不会马上看到上面状况,须要等100s以后两个消费者都commit以后才能看到上面的状况。

 

 

四、 整合Spring实现消息发送和接收,在整合以前咱们须要添加jar包,须要的jar包以下

image

下面这个是我我的在测试开发的时候使用的jar文件,仅供参考。

这些jar包能够在D:\apache-activemq-5.8.0\lib这个lib目录中找到,添加完jar包后就开始编码工做。

消息发送者

 

 
  
package com.xx.mq.spring;


import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
 
/**
 *  Spring JMSTemplate 消息发送者<br>
 *  将JMS整合到spring上面进行开发
 * @author hao
 * @since    2015-9-24
 * @file MessageReceiver.java
 * @package com.xx.mq.jms
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @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 {
                TextMessage message = session.createTextMessage();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date=formatter.format(new Date());
                String text="current system time: "+date;
                message.setText(text);
                System.out.println(text);
                return message;
            }
        });
    }
}
 
  

 

 
 

 

消息接收者

 

 
  
package com.xx.mq.spring;


import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
 
/**
 *  Spring JMSTemplate 消息接收者<br>
 *  将JMS整合到spring上面进行开发
 * @author hao
 * @since    2015-9-24
 * @file MessageReceiver.java
 * @package com.xx.mq.jms
 * @project ActiveMQ-5.8
 * @blog http://cnblogs.com/xiohao
 * @email 1261245595@qq.com
 * @version 1.0
 */
public class Receiver {
 
    public static void main(String[] args) throws JMSException {
        ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");  
          
        JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");  
        while(true) {  
        	//设置10s超时时间
        	jmsTemplate.setReceiveTimeout(1000*10);
            TextMessage text =   (TextMessage) jmsTemplate.receive();  
            if(text==null)
            	break;
            //接收到相应的消息
            System.out.println("收到消息:" + text.getText());  
        }  
    }
}
 
  

 

 
 

 

这里主要是用到了JmsTemplate这个消息模板,这个对象在spring的IoC容器中管理,因此要从spring的容器上下文中获取。下面看看spring的配置文件applicationContext-beans.xml内容:

 

 
  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    
<!--     链接池 
    <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">  
        <property name="connectionFactory">  
            <bean class="org.apache.activemq.ActiveMQConnectionFactory">  
                <property name="brokerURL" value="tcp://localhost:61616" />  
            </bean>  
        </property>  
    </bean>  
       -->
    <!-- 链接工厂 -->
    <bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
        <property name="brokerURL" value="tcp://localhost:61616" />  
    </bean>  
    
    <!-- 配置消息目标 -->
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">  
        <!-- 目标,在ActiveMQ管理员控制台建立 http://localhost:8161/admin/queues.jsp -->
        <constructor-arg index="0" value="mq.queue" />  
    </bean>  
 
    <!-- 消息模板 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
        <property name="connectionFactory" ref="activeMQConnectionFactory" />  
        <property name="defaultDestination" ref="destination" />  
        <property name="messageConverter">  
            <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
        </property>  
    </bean>  
</beans>
 
  

 运行效果同以前的效果是一一致的,这里就不进行展现了~~~

 
 

 

这里的整合就比较简单了,若是你是web工程,那你在须要用jms的时候,只需用注入jmsTemplate便可。

到此mq的基础入门讲解已经所有讲解完毕了。有任何问题,欢迎留言探讨~~

 

参考连接:http://www.cnblogs.com/linjiqin/category/486898.html

              http://blog.csdn.net/zbw18297786698/article/category/6496088

相关文章
相关标签/搜索