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里一个非常重要的核心类,它是提供某种优化消息存储的方法.消息中间件的实现一般都是当消费者准备好消费消息的时候,它会从持久化存储中一批一批的读取 ... 
随机推荐
- 转:c++ Oracle OCCI 编程
			原地址http://blog.sina.com.cn/s/blog_53a72add01015zj4.html 找不到具体的出处,只好不写了. OCCI数据库ORACLE编程步骤1. 配置环境(1) ... 
- AC日记——Dylans loves tree hdu 5274
			Dylans loves tree Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Othe ... 
- 51nod 1088 最长回文子串 【中心拓展法/输出长度和路径】
			1088 最长回文子串 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注 回文串是指aba.abba.cccbccc.aaaa这种左右对称的字符串. 输入一个字 ... 
- hdu6223(后缀数组)
			题意: 给一个长度为n的字符串s[0..n-1],但i的后继不再是i+1,而是(i*i+1)%n,求所有长度为n的“子串”中,字典序最大的是谁 n<=150000 分析: 如果是一般的字符串,那 ... 
- Java -----transient 和static
			越来越喜欢深究java基础了,讲讲 transient 和static 对序列化的影响.废话少说,直接上代码就可以了 package serializable; import java.io.Ser ... 
- SQL Server 监控系列 —— 二
			http://www.cnblogs.com/bhtfg538/archive/2011/01/21/1939706.html 
- EventBus3.0使用笔记.md
			事件总线这个其实没什么好说的,除了已经ondestroy的fragment或者activity不能接受外,只要定义了的都能接收消息 代码如下,需要注意的一点就是接收的监听事件必须用public修饰并且 ... 
- 详解在Visual Studio中使用git版本系统(图文)
			http://www.codesky.net/article/201111/123474.html 这篇教程的预期,是希望没有任何版本使用基础的新手也可以掌握,所以细节较多,不当之处,欢迎指正. 第一 ... 
- [c++菜鸟]《Accelerate C++》习题解答
			第0章 0-0 编译并运行Hello, world! 程序. #include <iostream> using namespace std; int main() { cout < ... 
- myeclipse2014破解
			去年出现的struts2 bug问题,在过去的项目中一直没做调整,前段时间发现受到影响了.本想这个bug都已经这么长时间了,工具中的包应该也已经被替换了吧,于是下载了最新的myeclipse2014, ... 
