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里一个非常重要的核心类,它是提供某种优化消息存储的方法.消息中间件的实现一般都是当消费者准备好消费消息的时候,它会从持久化存储中一批一批的读取 ...
随机推荐
- LeetCode OJ--Permutation Sequence *
求第k个排列. 刚开始按照一个排列一个排列的求,超时. 于是演算了一下,发下有数学规律,其实就是康托解码. 康托展开:全排列到一个自然数的双射 X=an*(n-1)!+an-1*(n-2)!+...+ ...
- [翻译] NumSharp的数组切片功能 [:]
原文地址:https://medium.com/scisharp/slicing-in-numsharp-e56c46826630 翻译初稿(英文水平有限,请多包涵): 由于Numsharp新推出了数 ...
- guake使用
1. 安装:sudo apt-get install guake 2. 在终端输入guake 3. f12:显示/隐藏 4. f11:全屏/正常屏切换 5. f2:重命名终端名 6. 还可以查看修改快 ...
- 关于main()
1.在c语言中: int main( void ) int main( int argc, char *argv[] ) 如果不需要从命令行中获取参数,请用int main(void) :否则请用in ...
- android添加桌面悬浮窗
1. 添加权限 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> 2. ...
- Spring Cloud Eureka 自我保护机制实战分析
前些天栈长在Java技术栈微信公众号分享过 Spring Cloud Eureka 的系列文章: Spring Cloud Eureka 自我保护机制 Spring Cloud Eureka 常用配置 ...
- python学习笔记1-numpy/enumerate
1. np.size和np.prod import numpy as np x = np.zeros((3, 5, 2), dtype=np.complex128) # ndarray.size is ...
- Mac item2 配色,大小写敏感及常用快捷键
http://blog.csdn.net/lainegates/article/details/38313559 目录(?)[-] 配色 大小写敏感 快捷揵 item2是mac下非常好用的一款终端 ...
- oracle 查看各表空间剩余量
1.查看所有表空间大小.剩余量: select dbf.tablespace_name,dbf.totalspace "总量(M)",dbf.totalblocks as 总块数, ...
- 第十讲_图像检索 Image Retrieval
第十讲_图像检索 Image Retrieval 刚要 主要是图像预处理和特征提取+相似度计算 相似颜色检索 算法结构 颜色特征提取:统计图片的颜色成分 颜色特征相似度计算 色差距离 发展:欧式距离- ...