ActiviteMQ分析
消息示例
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.wsheng.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;
/**
* <b>function:</b> 消息发送者
* @author Josh, Wang(Sheng)
* @file MessageSender.java
* @package com.wsheng.mq.jms
* @project ActiveMQ-5.8
* @email josh_wang23@hotmail.com
* @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.jsp
public static final String DESTINATION = "wsheng.mq.queue";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.wsheng.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;
/**
* <b>function:</b> 消息接收者
* @author Josh, Wang(Sheng)
* @file MessageSender.java
* @package com.wsheng.mq.jms
* @project ActiveMQ-5.8
* @email josh_wang23@hotmail.com
* @version 1.0
*/
public class MessageReceiver {// tcp 地址
public static final String BROKER_URL = "tcp://localhost:61616";// 目标,在ActiveMQ管理员控制台创建 http://localhost:8161/admin/queues.jsp
public static final String DESTINATION = "wsheng.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 ms
Message 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队列方式发送点对点消息数据
发送方
packagecom.wsheng.mq.jms;
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;
/**
* <b>function:</b> Queue 方式消息发送者
* @author Josh, Wang(Sheng)
* @file MessageSender.java
* @package com.wsheng.mq.jms
* @project ActiveMQ-5.8
* @email josh_wang23@hotmail.com
* @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.jsp
public static final String DESTINATION = "wsheng.mq.queue";/**
* <b>function:</b> 发送消息
* @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.wsheng.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;
/**
* <b>function:</b> 消息接收者; 依赖hawtbuf-1.9.jar
* @author Josh, Wang(Sheng)
* @file MessageSender.java
* @package ccom.wsheng.mq.queue
* @project ActiveMQ-5.8
* @email josh_wang23@hotmail.com
* @version 1.0
*/
public class QueueReceiver {// tcp 地址
public static final String BROKER_URL = "tcp://localhost:61616";// 目标,在ActiveMQ管理员控制台创建 http://localhost:8161/admin/queues.jsp
public static final String TARGET = "wsheng.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.wsheng.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;
/**
* <b>function:</b> Queue 方式消息发送者
* @author Josh, Wang(Sheng)
* @file MessageSender.java
* @package com.wsheng.mq.jms
* @project ActiveMQ-5.8
* @email josh_wang23@hotmail.com
* @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.jsp
public static final String DESTINATION = "wsheng.mq.topic";/**
* <b>function:</b> 发送消息
* @author Josh, Wang(Sheng)
* @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.wsheng.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;
/**
* <b>function:</b> 消息接收者; 依赖hawtbuf-1.9.jar
* @author Josh, Wang(Sheng)
* @file MessageSender.java
* @package com.wsheng.mq.jms
* @project ActiveMQ-5.8
* @email josh_wang23@hotmail.com
* @version 1.0
*/
public class TopicReceiver {// tcp 地址
public static final String BROKER_URL = "tcp://localhost:61616";// 目标,在ActiveMQ管理员控制台创建 http://localhost:8161/admin/queues.jsp
public static final String TARGET = "wsheng.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.wsheng.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;
/**
* <b>function:</b> Spring JMSTemplate 消息发送者
* @author Josh, Wang(Sheng)
* @file MessageSender.java
* @package com.wsheng.mq.jms
* @project ActiveMQ-5.8
* @email josh_wang23@hotmail.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 {MapMessage message = session.createMapMessage();message.setString("message", "current system time: " + new Date().getTime());return message;
}});}}消息接收者
package com.wsheng.mq.spring.support;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
/**
* <b>function:</b> Spring JMSTemplate 消息接收者
* @author Josh, Wang(Sheng)
* @file MessageSender.java
* @package com.wsheng.mq.jms
* @project ActiveMQ-5.8
* @email josh_wang23@hotmail.com
* @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) {
Map<String, Object> map = (Map<String, Object>) jmsTemplate.receiveAndConvert();System.out.println("收到消息:" + map.get("message"));}}}这里主要是用到了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/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">
<!-- 连接池 -->
<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="wsheng.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即可。
上一篇: 原生js实现可拖动的登录框效果
下一篇: 微信小程序form表单组件示例代码
推荐阅读
-
PHP模板引擎Smarty内建函数foreach,foreachelse用法分析
-
STL学习(自学手册+源码分析)之 map multimap
-
实例分析Access中数据表的自动重新联接
-
Queue、Deque、ArrayDeque源码分析
-
Discuz7.2版的faq.php SQL注入漏洞分析
-
详细讲解用SQLyog来分析MySQL数据库_MySQL
-
php缓冲输出实例分析
-
PHP 性能分析与实验:性能的微观分析(1)
-
《深入分析Java Web技术内幕》读书笔记 博客分类: 技术总结研究报告 《深入分析Java Web技术内幕》读书笔记
-
php中常量DIRECTORY_SEPARATOR用法深入分析,separator