ActiveMQ的消息的(含附件)发送和接收使用
首先介绍一下ActiveMQ的版本:apache-activemq-5.10.2
启动MQ:activemq.bat
下面来编写MQ的发送类:
里面的发送ip和模式名称可以根据具体的实际情况填写。
SendMessageByMq.java
public class SendMessageByMq {
public static void main(String[] args) {
String url = "";
// String url = "D:/mqfile/84.zip";
File file = new File(url);// 发送的文件
System.out.println("file=======" + file);
String sendType = "2";// 发送的类型 1发布一对一 ;2订阅一对多
String isNotFile = "false";// 是否有附件true有 false没有
String ip = ContentUtils.MQ_SEND_IP;// 发送ip
String modeName = ContentUtils.MQ_POINT_QUEUENAME;// 模式名称
String json = "[{\"name\":\"40013386.jpg\",\"url\":\"http://h.hiphotos.baidu.com/baik23e5.jpg\"}]";// 要发送的json数据
// 发送方法
String result = send(sendType, ip, modeName, json, file);
if (result.equals("success")) {
try {
System.out.println("开始接收1");
// 接收方法
ReceiveMessageByMq.receive(sendType, ip, isNotFile, modeName);
} catch (JMSException e) {
e.printStackTrace();
}
}
}
/**
*
*
* Title String Description
*
* @author jacun
* @date 2017-4-11上午11:44:17
* @param sendType
* 发送类型 1发布一对一 ;2订阅一对多
* @param ipport
* 发送ip和端口
* @param modeName
* 模式名称
* @param jsonData
* 要发送的json数据
* @param file
* 发送的文件
* @return
*/
public static String send(String sendType, String ip, String modeName,
String jsonData, File file) {
String str = null;
System.out.println("开始发送1");
try {
// 获取 ConnectionFactory,ConnectionFactory:连接工厂,JMS用它创建连接
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://"
+ ip
+ ":61616?jms.blobTransferPolicy.defaultUploadUrl=http://"
+ ip + ":8161/fileserver/");
// 创建 Connection,Connection:JMS客户端到JMS Provider的连接
Connection connection = connectionFactory.createConnection();
connection.start();
// 创建 Session,Session:一个发送或接收消息的线程
ActiveMQSession session = (ActiveMQSession) connection
.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 创建 Destination,Destination:消息的目的地;消息发送给谁.
// Destination destination = null;
// 判断是点对点1还是发布订阅2
if ("2".equals(sendType)) {
System.out.println("一对多发布2");
createTopic(session, modeName, jsonData, file);
} else {
System.out.println("一对一发布2");
// 点对点发布
createQueue(session, modeName, jsonData, file);
}
session.close();
// 不关闭 Connection, 程序则不退出
connection.close();
// 发送完成删除文件
// if (file != null) {
// if (file.exists()) {
// file.delete();
// }
// }
str = "success";
return str;
} catch (JMSException e) {
e.printStackTrace();
str = "fail";
return str;
}
}
private static void createQueue(ActiveMQSession session, String modeName,
String jsonData, File file) {
try {
Destination destination = session.createQueue(modeName);
// 创建 Producer,MessageProducer:消息发送者
MessageProducer producer = session.createProducer(destination);
// 设置持久性的话,文件也可以先缓存下来,接收端离线再连接也可以收到文件
producer.setDeliveryMode(DeliveryMode.PERSISTENT);// 设置为持久性
if (file.length() > 0) {
System.out.println("一对一上传文件3");
// 构造 blobMessage,用来传输文件
isFileTransfer(producer, session, file, jsonData);
} else {
System.out.println("一对一无文件3");
notFileTransfer(producer, session, jsonData);
}
} catch (JMSException e) {
e.printStackTrace();
}
}
// 点对点无文件发送
private static void notFileTransfer(MessageProducer producer,
ActiveMQSession session, String jsonData) {
try {
TextMessage message = session.createTextMessage();
message.setStringProperty("sendType", "1");
message.setStringProperty("jsonData", jsonData);
message.setStringProperty("isNotFile", "false");
// 设置该消息的超时时间(有效期)
producer.setTimeToLive(60000);
// 发送
producer.send(message);
producer.close();
System.out.println("发送成功无文件4");
} catch (JMSException e) {
e.printStackTrace();
}
}
// 点对点有文件发送
private static void isFileTransfer(MessageProducer producer,
ActiveMQSession session, File file, String jsonData) {
try {
BlobMessage blobMessage = session.createBlobMessage(file);
blobMessage.setStringProperty("sendType", "1");
blobMessage.setStringProperty("jsonData", jsonData);
blobMessage.setStringProperty("isNotFile", "true");
// 设置该消息的超时时间(有效期)
producer.setTimeToLive(60000);
// 发送
producer.send(blobMessage);
producer.close();
System.out.println("发送成功有文件4");
} catch (JMSException e) {
e.printStackTrace();
}
}
private static void createTopic(ActiveMQSession session, String modeName,
String jsonData, File file) {
try {
Topic topic = session.createTopic(modeName);
MessageProducer producer = session.createProducer(topic);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
if (file.length() > 0) {
System.out.println("一对多上传文件3");
// 构造 blobMessage,用来传输文件
isFileTransfer(producer, session, file, jsonData);
} else {
System.out.println("一对多无文件3");
notFileTransfer(producer, session, jsonData);
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
ActiveMQ的接收类:
里面的发送ip和模式名称可以根据具体的实际情况填写。
ReceiveMessageByMq.java
public class ReceiveMessageByMq {
public static void main(String[] args) {
String receiveType = "1";// 接收的类型 1发布一对一 ;2订阅一对多
String isNotFile = "true";// 是否有附件
String ip = ContentUtils.MQ_RECEIVE_IP;// 接收ip
String modeName = ContentUtils.MQ_POINT_QUEUENAME;// 模式名称
try {
receive(receiveType, ip, isNotFile, modeName);
} catch (JMSException e) {
e.printStackTrace();
}
}
/**
*
*
* Title void Description
*
* @author jacun
* @param modeName
* @param ip
* @param receiveType
* @date 2017-4-11上午10:43:10
* @throws JMSException
*/
public static void receive(String receiveType, String ip, String isNotFile,
String modeName) throws JMSException {
System.out.println("开始接收2");
// 获取 ConnectionFactory
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://" + ip + ":61616");
// 创建 Connection
Connection connection = connectionFactory.createConnection();
connection.start();
// 创建 Session
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
// 创建 Destinatione
// 判断是一对一还是一对多
if ("2".equals(receiveType)) {
// 一对多
System.out.println("一对多接收数据3");
receiveTopic(session, isNotFile, modeName);
} else {
// 一对一
System.out.println("一对一接收数据3");
receiveQueue(session, isNotFile, modeName);
}
}
private static void receiveTopic(Session session, String isNotFile,
String modeName) {
try {
final String isFile = isNotFile;
Destination destination = session.createTopic(modeName);
// 创建 Consumer
MessageConsumer consumer = session.createConsumer(destination);
// 注册消息监听器,当消息到达时被触发并处理消息
consumer.setMessageListener(new MessageListener() {
// 监听器中处理消息
public void onMessage(Message message) {
if ("true".equals(isFile)) {
System.out.println("有文件接收数据4");
ReceiveMessageByMq.receiveFile(message);
} else {
System.out.println("无文件接收数据4");
ReceiveMessageByMq.receiveData(message);
}
}
});
} catch (JMSException e) {
e.printStackTrace();
}
}
private static void receiveQueue(Session session, String isNotFile,
String modeName) {
try {
final String isFile = isNotFile;
Destination destination = session.createQueue(modeName);
// 创建 Consumer
MessageConsumer consumer = session.createConsumer(destination);
// 注册消息监听器,当消息到达时被触发并处理消息
consumer.setMessageListener(new MessageListener() {
// 监听器中处理消息
public void onMessage(Message message) {
if ("true".equals(isFile)) {
System.out.println("有文件接收数据4");
ReceiveMessageByMq.receiveFile(message);
} else {
System.out.println("无文件接收数据4");
ReceiveMessageByMq.receiveData(message);
}
}
});
} catch (JMSException e) {
e.printStackTrace();
}
}
protected static void receiveData(Message message) {
String sendType = null;
String jsonData = null;
try {
TextMessage msg = (TextMessage) message;
sendType = msg.getStringProperty("sendType");
jsonData = msg.getStringProperty("jsonData");
} catch (JMSException e) {
e.printStackTrace();
}
System.out.println("无文件接收成功5");
System.out.println(sendType);
System.out.println(jsonData);
}
private static void receiveFile(Message message) {
String sendType = null;
String jsonData = null;
if (message instanceof BlobMessage) {
BlobMessage blobMessage = (BlobMessage) message;
try {
String path = CreateZipFile.createZip("test");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("请指定文件保存位置");
fileChooser.setSelectedFile(new File(path));
File file = fileChooser.getSelectedFile();
OutputStream os = new FileOutputStream(file);
InputStream inputStream = blobMessage.getInputStream();
// 写文件,你也可以使用其他方式
byte[] buff = new byte[256];
int len = 0;
while ((len = inputStream.read(buff)) > 0) {
os.write(buff, 0, len);
}
os.close();
System.out.println("有文件接收成功5");
sendType = blobMessage.getStringProperty("sendType");
jsonData = blobMessage.getStringProperty("jsonData");
System.out.println(sendType);
System.out.println(jsonData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
亲测好使,这两个工具类包含了发送和接收的方法,而且可以点对点或者发布订阅、有无附件均可,对了还有一点,ActiveMQ需要的jar包,网上信息很多!
补充:补充一个mq接收端自动连接到mq服务器的方法:
那就是将连接方式换一下就可以了:
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin","failover:("tcp://" + ip + ":61616")?initialReconnectDelay=1000&maxReconnectDelay=30000");
ActiveMQ的消息的(含附件)发送和接收使用的更多相关文章
- ACtiveMQ中间件-消息的接收和发送
一.发送消息基本步骤 (1)启动ActiveMQ的的activemq.bat批处理文件或BrokerService节点 (2)创建连接使用的工厂类ActiveMQConnectionFactory通过 ...
- C# 发送电子邮件(含附件)用到的类 system.web.mail
主要是用到了System.Web.Mail命名空间,用到了此空间的三个类,分别是: ●MailMessage类,用于构造电子邮件●MailAttachment类,用于构造电子邮件附件●SmtpMail ...
- ActiveMQ 实现消息接收发送
一.接收者 package com.demo.initservice; import javax.jms.Connection; import javax.jms.ConnectionFactory; ...
- ActiveMQ实例1--简单的发送和接收消息
一.环境准备 1,官网http://activemq.apache.org/下载最新版本的ActiveMQ,并解压 2,打开对应的目录,在Mac环境下,一般可以运行命令: cd /Users/***/ ...
- java邮件发送(含附件)
1. [代码]java邮件发送(含附件)疯狂的IT人站长整理的:利用Java发送邮件(含附件)的例子:1.邮件发送的配置propertity文件内容如下:(utils.properties文件放在sr ...
- ActiveMQ 发送和接收消息
一.添加 jar 包 <dependency> <groupId>org.apache.activemq</groupId> <artifactId>a ...
- ActiveMQ发消息和收消息
来自:http://blog.163.com/chengwei_1104/blog/static/53645274201382315625329/ ActiveMQ 是Apache出品,最流行的,能力 ...
- javamail模拟邮箱功能发送电子邮件-中级实战篇【新增附件发送方法】(javamail API电子邮件实例)
引言: JavaMail jar包下载地址:http://java.sun.com/products/javamail/downloads/index.html 此篇是紧随上篇文章而封装出来的,阅读本 ...
- ActiveMQ之消息指针
消息指针(Message cursor)是activeMQ里一个非常重要的核心类,它是提供某种优化消息存储的方法.消息中间件的实现一般都是当消费者准备好消费消息的时候,它会从持久化存储中一批一批的读取 ...
随机推荐
- 安装apache2.4和php7.1的方法记录
下载扩展 这是PHP官方扩展下载的地址 http://pecl.php.net 点击下载dll文件,放到php的ext目录. 看这个说明下载你PHP版本支持的版本.
- hdu 1195(搜索)
Open the Lock Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Tot ...
- Ruby自动化测试(操作符的坑)
事情是这样的: times++ @ddr = DDR::DDR.new() 执行到这里的时候,总是报错:'+@' undefied method.刚开始的时候以为是机器在重启过程中一些不稳定函数调用或 ...
- Drupal 有用的模块
投票模块drigg https://www.drupal.org/project/drigg
- HDU 3068 Manacher
题目链接:http://hdu.hustoj.com/showproblem.php?pid=3068 今天学习一下马拉车算法,虽然mg讲过,但是没有系统去学. 算法学习:参考博客 马拉车模板题. # ...
- 洛谷—— P1849 [USACO12MAR]拖拉机Tractor
https://www.luogu.org/problemnew/show/P1849 题目描述 After a long day of work, Farmer John completely fo ...
- ubuntu下某些文件目录
1.#include <stdio.h> 2.#include <stdlib.h> stdio.h和stdlib.h的路径:/usr/include
- DNA的复制
半保留复制 DNA分子复制时, DNA分子的双螺旋将解开, 互补的碱基之间的氢键断裂, 解开的两条单链作为复制的模板, 游离的脱氧核苷酸依据碱基互补配对的原则, 通过形成氢键结合到作为模板的单链上. ...
- 45个非常有用的Oracle查询语句(转自开源中国社区)
日期/时间 相关查询 获取当前月份的第一天 运行这个命令能快速返回当前月份的第一天.你可以用任何的日期值替换 “SYSDATE”来指定查询的日期. SELECT TRUNC (SYSDATE, 'MO ...
- 如何直接打开使用locate等查找到的文件
很多的时候需要使用locate去定位文件,找到了文件之后接下来就是使用相应的文本编辑工具如gvim进行打开. 这个时候最烦心的就是去复制一大长串的地址了. 如果能让定位和打开一体操作就最好了,这就需要 ...