分布式消息中间件:ActiveMq
ActiveMq是apache出品的,最流行,功能强大的集成模式的开源服务器。ActiveMq是快速的,支持许多跨语言的客户端和协议,具有易于使用的企业集成模式和许多高级特性,同时完全支持JMS1.1,以及J2EE1.4,ActiveMq是在Apache2.0的许可下发布。
特性:
*支持许多跨语言的客户端和协议(Java, C, C++, C#, Ruby, Perl, Python, PHP)
-FTP:文件传输协议
-STOMP:简单流文本定向消息协议,允许SMTOP客户端和任意的消息代理Broker进行交互。(支持)
-SMTP:邮件传输协议
-AMQP:提供统一消息服务的应用层的标准协议(支持)
-MQTT:是一个消息队列遥测传输协议,是IBM开发的用于即时通讯的协议。(支持)
-Openwire:是ActiveMq自己跨语言的协议,允许本地访问通过不同的语言和平台访问ActiveMq.在ActiveMq4.0之后java是ActiveMq默认支持的语言。
-ws协议:即webSocket协议。
-在JMS客户端和消息代理中完全支持企业集成模式
-支持许多高级特性,比如,消息组,虚拟目的地,组合目的地。
完整特性见官网。
ActiveMq的使用:
1.ActiveMq二进制文件解压,或者下载源码安装。
2.启动ActiveMq
第一种启动:命令shell中,更改为安装目录,并运行ActuMeq作为一个预先的过进程:
进入activeMq安装的bin目录: ./activemq console启动
第二种启动:命令shell中,更改为安装目录并运行ActudiMQ作为守护进程:
进入activemq安装的bin目录: ./active start
3.停止activemq:
进入activemq安装的bin目录: ./activemq stop
4.测试activemq的安装:8161端口是管理页面的默认端口(是一个内置的jetty容器),可以在这个管理界面监控activemq。
activemq的日志文件目录下的data目录:activemq.log(启动日志)
监听端口:activemq默认的端口是61616
activemq的文件目录:bin目录二进制文件执行的目录,conf配置文件的存放目录,data数据文件的存放目录,docs目录是activemq官网文档的目录。example目录是一个demo目录。webapps目录是web应用程序的目录。webapps-demo是web应用的demo目录。
例子:
JMS方式发送接收消息:
1.新建Active_JMS项目
2.引入activemq-all-5.8.0.jar(安转目录下)
3.启动activemq: 在bin目录下./activemq start
4.打开浏览器输入http://127.0.0.1:8161/admin
5.在管理界面点击Queues,输入refrain.mq点击create
package com.refrain.sender;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息生产者
*/
public class MessageSender {
// 定义发送次数
private static final int SEND_NUMS = 5;
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Destination destination = session.createQueue(DESTINATION);
// 创建消息生产者
MessageProducer messageProducer = session.createProducer(destination);
// 设置消息的持久化模式
messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMsg(session, messageProducer);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
private static void sendMsg(Session session, MessageProducer messageProducer) throws JMSException {
for(int i = 0; i<SEND_NUMS; i++) {
String message = "发送第" + (i + 1) +"消息";
TextMessage textMessage = session.createTextMessage(message);
System.out.println(message);
messageProducer.send(textMessage);
}
}
}
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息生产者
*/
public class MessageSender {
// 定义发送次数
private static final int SEND_NUMS = 5;
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Destination destination = session.createQueue(DESTINATION);
// 创建消息生产者
MessageProducer messageProducer = session.createProducer(destination);
// 设置消息的持久化模式
messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMsg(session, messageProducer);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
private static void sendMsg(Session session, MessageProducer messageProducer) throws JMSException {
for(int i = 0; i<SEND_NUMS; i++) {
String message = "发送第" + (i + 1) +"消息";
TextMessage textMessage = session.createTextMessage(message);
System.out.println(message);
messageProducer.send(textMessage);
}
}
}
7.新建MessageReceiver.java
package com.refrain.receiver;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息消费者
*/
public class MessageReceiver {
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Destination destination = session.createQueue(DESTINATION);
// 创建消息消费者
MessageConsumer messageConsumer = session.createConsumer(destination);
while (true) {
TextMessage message = (TextMessage) messageConsumer.receive(1000 * 100);
if(message != null) {
System.out.println("接收到:" + message.getText());
} else {
break;
}
}
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息消费者
*/
public class MessageReceiver {
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() {
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Destination destination = session.createQueue(DESTINATION);
// 创建消息消费者
MessageConsumer messageConsumer = session.createConsumer(destination);
while (true) {
TextMessage message = (TextMessage) messageConsumer.receive(1000 * 100);
if(message != null) {
System.out.println("接收到:" + message.getText());
} else {
break;
}
}
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
8.新建测试类:ActiveMqTest.java
package com.refrain.activemqtest;
import com.refrain.receiver.MessageReceiver;
import com.refrain.sender.MessageSender;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 20:47
* @Description:测试
*/
public class ActiveMqTest {
public static void main(String[] args) {
// 启动消息生产者
MessageSender.run();
// 启动消息消费者
MessageReceiver.run();
}
}
import com.refrain.receiver.MessageReceiver;
import com.refrain.sender.MessageSender;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 20:47
* @Description:测试
*/
public class ActiveMqTest {
public static void main(String[] args) {
// 启动消息生产者
MessageSender.run();
// 启动消息消费者
MessageReceiver.run();
}
}
9.运行main方法,输入:http://127.0.0.1:8161/admin/queues.jsp
Queue点对点方式发送接收消息:
过程和JMS形式的相似,不同点就是使用Queue形式创建连接工厂,创建连接,启动连接,创建会话,
创建消息生产者和消费者。
代码如下:
QueueSender.java:
package com.refrain.sender;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_Queue
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息生产者
*/
public class QueueSender {
// 定义发送次数
private static final int SEND_NUMS = 5;
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() {
QueueConnectionFactory connectionFactory = null;
QueueConnection connection = null;
QueueSession session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createQueueConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Queue queue = session.createQueue(DESTINATION);
// 创建消息生产者
javax.jms.QueueSender queueSender = session.createSender(queue);
// 设置消息的持久化模式
queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMsg(session, queueSender);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
private static void sendMsg(QueueSession session, javax.jms.QueueSender queueSender) throws JMSException {
for(int i = 0; i<SEND_NUMS; i++) {
String message = "发送第" + (i + 1) +"消息";
MapMessage mapMessage = session.createMapMessage();
mapMessage.setString("text", message);
mapMessage.setLong("time", System.currentTimeMillis());
System.out.println(message);
queueSender.send(mapMessage);
}
}
}
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_Queue
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息生产者
*/
public class QueueSender {
// 定义发送次数
private static final int SEND_NUMS = 5;
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() {
QueueConnectionFactory connectionFactory = null;
QueueConnection connection = null;
QueueSession session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createQueueConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Queue queue = session.createQueue(DESTINATION);
// 创建消息生产者
javax.jms.QueueSender queueSender = session.createSender(queue);
// 设置消息的持久化模式
queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMsg(session, queueSender);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
private static void sendMsg(QueueSession session, javax.jms.QueueSender queueSender) throws JMSException {
for(int i = 0; i<SEND_NUMS; i++) {
String message = "发送第" + (i + 1) +"消息";
MapMessage mapMessage = session.createMapMessage();
mapMessage.setString("text", message);
mapMessage.setLong("time", System.currentTimeMillis());
System.out.println(message);
queueSender.send(mapMessage);
}
}
}
QueueReceiver.java:
package com.refrain.receiver;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
/**
* @Program: ActiveMq_Queue
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息消费者
*/
public class QueueReceiver {
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() throws InterruptedException {
QueueConnectionFactory connectionFactory = null;
QueueConnection connection = null;
QueueSession session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createQueueConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Queue queue= session.createQueue(DESTINATION);
// 创建消息订阅者
javax.jms.QueueReceiver queueReceiver = session.createReceiver(queue);
queueReceiver.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if (message != null) {
MapMessage mapMessage = (MapMessage) message;
try {
System.out.println(mapMessage.getLong("time") + "接收:" + mapMessage.getString("text"));
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
Thread.sleep(1000 * 100);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
/**
* @Program: ActiveMq_Queue
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息消费者
*/
public class QueueReceiver {
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() throws InterruptedException {
QueueConnectionFactory connectionFactory = null;
QueueConnection connection = null;
QueueSession session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createQueueConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Queue queue= session.createQueue(DESTINATION);
// 创建消息订阅者
javax.jms.QueueReceiver queueReceiver = session.createReceiver(queue);
queueReceiver.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if (message != null) {
MapMessage mapMessage = (MapMessage) message;
try {
System.out.println(mapMessage.getLong("time") + "接收:" + mapMessage.getString("text"));
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
Thread.sleep(1000 * 100);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
ActiveMqTest.java:
package com.refrain.activemqtest;
import com.refrain.receiver.MessageReceiver;
import com.refrain.receiver.QueueReceiver;
import com.refrain.sender.MessageSender;
import com.refrain.sender.QueueSender;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 20:47
* @Description:测试
*/
public class ActiveMqTest {
public static void main(String[] args) throws InterruptedException {
/*
JMS方式发送接收消息
*/
// 启动消息生产者
//MessageSender.run();
// 启动消息消费者
//MessageReceiver.run();
/*
Queue方式发送接收消息
*/
// 启动消息生产者
QueueSender.run();
// 启动消息消费者
QueueReceiver.run();
}
}
import com.refrain.receiver.MessageReceiver;
import com.refrain.receiver.QueueReceiver;
import com.refrain.sender.MessageSender;
import com.refrain.sender.QueueSender;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 20:47
* @Description:测试
*/
public class ActiveMqTest {
public static void main(String[] args) throws InterruptedException {
/*
JMS方式发送接收消息
*/
// 启动消息生产者
//MessageSender.run();
// 启动消息消费者
//MessageReceiver.run();
/*
Queue方式发送接收消息
*/
// 启动消息生产者
QueueSender.run();
// 启动消息消费者
QueueReceiver.run();
}
}
Topic主题发布订阅消息:
过程和Queue形式的相似,不同点就是使用Queue形式创建连接工厂,创建连接,启动连接,创建会话,
,创建消息队列,建消息生产者和消费者。
代码如下:
TopicPublisher.java:
package com.refrain.sender;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_Topic
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息生产者
*/
public class TopicPublisher {
// 定义发送次数
private static final int SEND_NUMS = 5;
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() {
TopicConnectionFactory connectionFactory = null;
TopicConnection connection = null;
TopicSession session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createTopicConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Topic topic = session.createTopic(DESTINATION);
// 创建消息生产者
javax.jms.TopicPublisher topicPublisher = session.createPublisher(topic);
// 设置消息的持久化模式
topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMsg(session, topicPublisher);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
private static void sendMsg(TopicSession session, javax.jms.TopicPublisher topicPublisher) throws JMSException {
for(int i = 0; i<SEND_NUMS; i++) {
String message = "发送第" + (i + 1) +"消息";
MapMessage mapMessage = session.createMapMessage();
mapMessage.setString("text", message);
mapMessage.setLong("time", System.currentTimeMillis());
System.out.println(message);
topicPublisher.send(mapMessage);
}
}
}
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_Topic
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息生产者
*/
public class TopicPublisher {
// 定义发送次数
private static final int SEND_NUMS = 5;
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() {
TopicConnectionFactory connectionFactory = null;
TopicConnection connection = null;
TopicSession session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createTopicConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Topic topic = session.createTopic(DESTINATION);
// 创建消息生产者
javax.jms.TopicPublisher topicPublisher = session.createPublisher(topic);
// 设置消息的持久化模式
topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMsg(session, topicPublisher);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
private static void sendMsg(TopicSession session, javax.jms.TopicPublisher topicPublisher) throws JMSException {
for(int i = 0; i<SEND_NUMS; i++) {
String message = "发送第" + (i + 1) +"消息";
MapMessage mapMessage = session.createMapMessage();
mapMessage.setString("text", message);
mapMessage.setLong("time", System.currentTimeMillis());
System.out.println(message);
topicPublisher.send(mapMessage);
}
}
}
TopicSubscriber.java:
package com.refrain.receiver;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_Queue
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息消费者
*/
public class TopicSubScriber {
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() throws InterruptedException {
TopicConnectionFactory connectionFactory = null;
TopicConnection connection = null;
TopicSession session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createTopicConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Topic topic= session.createTopic(DESTINATION);
// 创建消息订阅者
TopicSubscriber topicSubScriber = session.createSubscriber(topic);
topicSubScriber.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if (message != null) {
MapMessage mapMessage = (MapMessage) message;
try {
System.out.println("时间:" + mapMessage.getLong("time") + "接收:" + mapMessage.getString("text"));
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
Thread.sleep(1000 * 100);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* @Program: ActiveMq_Queue
* @Auther: lijiamin
* @Date: 18-7-23 16:48
* @Description:消息消费者
*/
public class TopicSubScriber {
// 定义tcp代理
private static final String BROKER_URL = "tcp://127.0.0.1:61616";
// 定义消息队列发送的目标
private static final String DESTINATION = "refrain.mq";
public static void run() throws InterruptedException {
TopicConnectionFactory connectionFactory = null;
TopicConnection connection = null;
TopicSession session = null;
try {
// 创建连接工厂,参数1:activeMq连接的用户,参数2:activeMq连接的密码,参数3:activeMq连接的客户端地址
connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, BROKER_URL);
// 创建连接
connection = connectionFactory.createTopicConnection();
// 启动连接
connection.start();
// 建立会话
session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建消息队列
Topic topic= session.createTopic(DESTINATION);
// 创建消息订阅者
TopicSubscriber topicSubScriber = session.createSubscriber(topic);
topicSubScriber.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if (message != null) {
MapMessage mapMessage = (MapMessage) message;
try {
System.out.println("时间:" + mapMessage.getLong("time") + "接收:" + mapMessage.getString("text"));
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
Thread.sleep(1000 * 100);
session.commit();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
ActiveMqTest.java:
package com.refrain.activemqtest;
import com.refrain.receiver.MessageReceiver;
import com.refrain.receiver.QueueReceiver;
import com.refrain.receiver.TopicSubScriber;
import com.refrain.sender.MessageSender;
import com.refrain.sender.QueueSender;
import com.refrain.sender.TopicPublisher;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 20:47
* @Description:测试
*/
public class ActiveMqTest {
public static void main(String[] args) throws InterruptedException {
/*
JMS方式发送接收消息
*/
// 启动消息生产者
//MessageSender.run();
// 启动消息消费者
//MessageReceiver.run();
/*
Queue方式发送接收消息
*/
// 启动消息生产者
//QueueSender.run();
// 启动消息消费者
//QueueReceiver.run();
/*
Topic方式发布订阅消息
*/
// 启动消息发布者
TopicPublisher.run();
// 启动消息订阅者
TopicSubScriber.run();
}
}
import com.refrain.receiver.MessageReceiver;
import com.refrain.receiver.QueueReceiver;
import com.refrain.receiver.TopicSubScriber;
import com.refrain.sender.MessageSender;
import com.refrain.sender.QueueSender;
import com.refrain.sender.TopicPublisher;
/**
* @Program: ActiveMq_JMS
* @Auther: lijiamin
* @Date: 18-7-23 20:47
* @Description:测试
*/
public class ActiveMqTest {
public static void main(String[] args) throws InterruptedException {
/*
JMS方式发送接收消息
*/
// 启动消息生产者
//MessageSender.run();
// 启动消息消费者
//MessageReceiver.run();
/*
Queue方式发送接收消息
*/
// 启动消息生产者
//QueueSender.run();
// 启动消息消费者
//QueueReceiver.run();
/*
Topic方式发布订阅消息
*/
// 启动消息发布者
TopicPublisher.run();
// 启动消息订阅者
TopicSubScriber.run();
}
}
Spring中使用ActiveMq:Jms消息类型
1.新建项目:ActiveMqOnSpring(Spring项目)
2.引入activemq-all-5.8.0.jar依赖(安转目录下)以及activemq-spring.jar依赖(安转目录下的lib目录下)
3.新建Application_ActiveMq.xml
4.新建SpringSender.java:
package com.refrain.Sender;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Date;
/**
* @Program: ActiveMqOnSpring
* @Auther: lijiamin
* @Date: 18-7-24 12:13
* @Description:Spring使用AcitveMq
*/
public class SpringSender {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml");
JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");
jmsTemplate.send(new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
MapMessage mapMessage = session.createMapMessage();
mapMessage.setString("text", "当前时间:" + new Date().toString());
return mapMessage;
}
});
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Date;
/**
* @Program: ActiveMqOnSpring
* @Auther: lijiamin
* @Date: 18-7-24 12:13
* @Description:Spring使用AcitveMq
*/
public class SpringSender {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml");
JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");
jmsTemplate.send(new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
MapMessage mapMessage = session.createMapMessage();
mapMessage.setString("text", "当前时间:" + new Date().toString());
return mapMessage;
}
});
}
}
5.新建SpringReceiver.java:
package com.refrain.Receiver; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jms.core.JmsTemplate; import java.util.Map; /** * @Program: ActiveMqOnSpring * @Auther: lijiamin * @Date: 18-7-24 12:22 * @Description:Springreceiver使用ActiveMq */ public class SpringReceiver { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml"); JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate"); while (true) { Map
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jms.core.JmsTemplate; import java.util.Map; /** * @Program: ActiveMqOnSpring * @Auther: lijiamin * @Date: 18-7-24 12:22 * @Description:Springreceiver使用ActiveMq */ public class SpringReceiver { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("*.xml"); JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate"); while (true) { Mapmap = (Map ) jmsTemplate.receiveAndConvert(); System.out.println("收到消息:" + map.get("text")); } } } map = (Map ) jmsTemplate.receiveAndConvert(); System.out.println("收到消息:" + map.get("text")); } } }
SpringBoot使用ActiveMq:Jms消息类型
1.新建SpringBoot项目:ActiveMqonSpringBoot(Gradle项目)
2.建application.yaml
spring:
application:
name: activemq-demo
server:
port: 9090
application:
name: activemq-demo
server:
port: 9090
3.新建MessageSender.java
package com.refrain.sender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.jms.Queue;
/**
* @Program: activemqonspringboot
* @Auther: lijiamin
* @Date: 18-7-24 14:01
* @Description:消息发送方
*/
// 将发送方注册为一个Bean
@Component
// 开启定时任务
@EnableScheduling
public class MessageSender {
// 注册JMS消息模板
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
// 注册消息队列
@Autowired
private Queue queue;
// 每隔3秒发送一次消息
@Scheduled(fixedRate = 3000)
public void send() {
jmsMessagingTemplate.convertAndSend(this.queue, "测试消息队列:" + System.currentTimeMillis() / 1000);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.jms.Queue;
/**
* @Program: activemqonspringboot
* @Auther: lijiamin
* @Date: 18-7-24 14:01
* @Description:消息发送方
*/
// 将发送方注册为一个Bean
@Component
// 开启定时任务
@EnableScheduling
public class MessageSender {
// 注册JMS消息模板
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
// 注册消息队列
@Autowired
private Queue queue;
// 每隔3秒发送一次消息
@Scheduled(fixedRate = 3000)
public void send() {
jmsMessagingTemplate.convertAndSend(this.queue, "测试消息队列:" + System.currentTimeMillis() / 1000);
}
}
4.新建MessageQueue.java
package com.refrain.queue;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.jms.Queue;
/**
* @Program: activemqonspringboot
* @Auther: lijiamin
* @Date: 18-7-24 14:16
* @Description:定义一个消息队列
*/
@Component
public class MessageQueue {
@Bean
public Queue queue() {
return new ActiveMQQueue("activeMqOnSpringBoot");
}
}
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.jms.Queue;
/**
* @Program: activemqonspringboot
* @Auther: lijiamin
* @Date: 18-7-24 14:16
* @Description:定义一个消息队列
*/
@Component
public class MessageQueue {
@Bean
public Queue queue() {
return new ActiveMQQueue("activeMqOnSpringBoot");
}
}
5.新建MessageReceiver.java
package com.refrain.receiver;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.annotation.JmsListeners;
import org.springframework.stereotype.Component;
/**
* @Program: activemqonspringboot
* @Auther: lijiamin
* @Date: 18-7-24 14:19
* @Description:定义消息接收方
*/
@Component
public class MessageReceiver {
// 使用JmsListeners监听某个队列的消息是否有新的消息,如果有则打印出来
@JmsListeners(@JmsListener(destination = "activeMqOnSpringBoot"))
public void removeMessage(String msg) {
System.out.println("监听到的消息是:" + msg);
}
}
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.annotation.JmsListeners;
import org.springframework.stereotype.Component;
/**
* @Program: activemqonspringboot
* @Auther: lijiamin
* @Date: 18-7-24 14:19
* @Description:定义消息接收方
*/
@Component
public class MessageReceiver {
// 使用JmsListeners监听某个队列的消息是否有新的消息,如果有则打印出来
@JmsListeners(@JmsListener(destination = "activeMqOnSpringBoot"))
public void removeMessage(String msg) {
System.out.println("监听到的消息是:" + msg);
}
}
6.定义ActivemqonspringbootApplication.java:应用程序入口
package com.refrain.activemqonspringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;
import javax.jms.ConnectionFactory;
// 扫描注解类并注册为Bean
@SpringBootApplication(scanBasePackages = {"com.refrain"})
// 开启Jms
@EnableJms
public class ActivemqonspringbootApplication {
/**
* 将SpringBoot里面的消息添加到jms监听工厂
* @param connectionFactory jms连接工厂
* @param defaultJmsListenerContainerFactoryConfigurer 默认的监听配置
* @return
*/
@Bean
public JmsListenerContainerFactory> jmsListenerContainerFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer defaultJmsListenerContainerFactoryConfigurer) {
// 实例化一个默认的监听工厂
DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory = new DefaultJmsListenerContainerFactory();
// 使用默认的监听配置注册默认的监听工厂到连接工厂
defaultJmsListenerContainerFactoryConfigurer.configure(defaultJmsListenerContainerFactory, connectionFactory);
return defaultJmsListenerContainerFactory;
}
/**
* @return 定义一个消息转换器否则会抛消息转换异常的错误
*/
/*@Bean // Serialize message content to json using TextMessage
public MessageConverter jacksonJmsMessageConverter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("_type");
return converter;
}*/
public static void main(String[] args) {
SpringApplication.run(ActivemqonspringbootApplication.class, args);
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;
import javax.jms.ConnectionFactory;
// 扫描注解类并注册为Bean
@SpringBootApplication(scanBasePackages = {"com.refrain"})
// 开启Jms
@EnableJms
public class ActivemqonspringbootApplication {
/**
* 将SpringBoot里面的消息添加到jms监听工厂
* @param connectionFactory jms连接工厂
* @param defaultJmsListenerContainerFactoryConfigurer 默认的监听配置
* @return
*/
@Bean
public JmsListenerContainerFactory> jmsListenerContainerFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer defaultJmsListenerContainerFactoryConfigurer) {
// 实例化一个默认的监听工厂
DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory = new DefaultJmsListenerContainerFactory();
// 使用默认的监听配置注册默认的监听工厂到连接工厂
defaultJmsListenerContainerFactoryConfigurer.configure(defaultJmsListenerContainerFactory, connectionFactory);
return defaultJmsListenerContainerFactory;
}
/**
* @return 定义一个消息转换器否则会抛消息转换异常的错误
*/
/*@Bean // Serialize message content to json using TextMessage
public MessageConverter jacksonJmsMessageConverter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("_type");
return converter;
}*/
public static void main(String[] args) {
SpringApplication.run(ActivemqonspringbootApplication.class, args);
}
}
build.gradle:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.refrain'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile(
'org.springframework.boot:spring-boot-starter-web',
'org.springframework.boot:spring-boot-starter-activemq'
)
testCompile('org.springframework.boot:spring-boot-starter-test')
}
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.refrain'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile(
'org.springframework.boot:spring-boot-starter-web',
'org.springframework.boot:spring-boot-starter-activemq'
)
testCompile('org.springframework.boot:spring-boot-starter-test')
}