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里一个非常重要的核心类,它是提供某种优化消息存储的方法.消息中间件的实现一般都是当消费者准备好消费消息的时候,它会从持久化存储中一批一批的读取 ...
随机推荐
- hdu 5459(递推好题)
Jesus Is Here Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 65535/102400 K (Java/Others)To ...
- TensorFlow——tensorflow指定CPU与GPU运算
1.指定GPU运算 如果安装的是GPU版本,在运行的过程中TensorFlow能够自动检测.如果检测到GPU,TensorFlow会尽可能的利用找到的第一个GPU来执行操作. 如果机器上有超过一个可用 ...
- POJ 3268 Silver Cow Party 最短路
原题链接:http://poj.org/problem?id=3268 Silver Cow Party Time Limit: 2000MS Memory Limit: 65536K Total ...
- ADO如何记录SQL日志
ADO如何记录SQL日志 procedure TfrmDM.ADOConnection1WillExecute(Connection: TADOConnection; var CommandText: ...
- C# 通过WebService方式 IIS发布网站 上传文件到服务器[转]
http://blog.sina.com.cn/s/blog_517cae3c0102v0y7.html 应用场景:要将本地的文件 上传到服务器的虚拟机上 网络环境:公司局域网(如下图中第二种) 开发 ...
- Mysql5.6审计功能
1. 前言 为了安全和操作的可追溯性考虑,越来越多的公司增加了审计功能.mysql5.5推出了相关的审计功能,到5.6.20功能进一步完好.算是勉强可用了.尽管细粒度方面做的不是太好. ...
- sql的一些知识_高级
1.视图 http://www.cnblogs.com/wang666/p/7885934.html 2.存储过程 http://www.cnblogs.com/wang666/p/7920748.h ...
- hibernate的注解装配
1.多对多,(中间表不用映射) @ManyToMany @JoinTable(name = "中间表名", joinColumns = { @JoinColumn(name = & ...
- at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:)
错误提示 错误原因 參考链接 错误提示: at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:) 在Andro ...
- Amazon SNS移动推送更新——新增百度云推送和Windows平台支持
Amazon SNS(Simple Notification Service)是一种基于云平台的消息通知和推送服务. SNS提供简单的 Web 服务接口和基于浏览器的管理控制台让用户可以简易设置.执行 ...