ActiveMQ
1.下载ActiveMQ去官方网站下载:
2.运行ActiveMQ解压缩apache-activemq-5.11.1-bin.zip,然后双击apache-activemq-5.11.1\bin\activemq.bat运行ActiveMQ程序。
启动ActiveMQ以后,登陆::8161/admin/,创建一个Queue,命名为FirstQueue。
3.创建Eclipse项目并运行创建project:MQ,并导入apache-activemq-5.11.1\lib目录下需要用到的jar文件,项目结构如下图所示:
3.1.Sender.java1 package activeMQ; 2 import javax.jms.Connection; 3 import javax.jms.ConnectionFactory; 4 import javax.jms.DeliveryMode; 5 import javax.jms.Destination; 6 import javax.jms.MessageProducer; 7 import javax.jms.Session; 8 import javax.jms.TextMessage; 9 10 import org.apache.activemq.ActiveMQConnection; 11 import org.apache.activemq.ActiveMQConnectionFactory; 12 public class Sender { 13 private static final int SEND_NUMBER = 10; 14 15 public static void main(String[] args) { 16 // ConnectionFactory :连接工厂,JMS 用它创建连接 17 ConnectionFactory connectionFactory; 18 // Connection :JMS 客户端到JMS Provider 的连接 19 Connection connection = null; 20 // Session: 一个发送或接收消息的线程 21 Session session; 22 // Destination :消息的目的地;消息发送给谁. 23 Destination destination; 24 // MessageProducer:消息发送者 25 MessageProducer producer; 26 // TextMessage message; 27 // 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar 28 connectionFactory = new ActiveMQConnectionFactory( 29 ActiveMQConnection.DEFAULT_USER, 30 ActiveMQConnection.DEFAULT_PASSWORD, 31 "tcp://localhost:61616"); 32 try { 33 // 构造从工厂得到连接对象 34 connection = connectionFactory.createConnection(); 35 // 启动 36 connection.start(); 37 // 获取操作连接 38 session = connection.createSession(Boolean.TRUE, 39 Session.AUTO_ACKNOWLEDGE); 40 // 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置 41 destination = session.createQueue("FirstQueue"); 42 // 得到消息生成者【发送者】 43 producer = session.createProducer(destination); 44 // 设置不持久化,此处学习,实际根据项目决定 45 producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); 46 // 构造消息,此处写死,项目就是参数,或者方法获取 47 sendMessage(session, producer); 48 session.commit(); 49 } catch (Exception e) { 50 e.printStackTrace(); 51 } finally { 52 try { 53 if (null != connection) 54 connection.close(); 55 } catch (Throwable ignore) { 56 } 57 } 58 } 59 60 public static void sendMessage(Session session, MessageProducer producer) 61 throws Exception { 62 for (int i = 1; i <= SEND_NUMBER; i++) { 63 TextMessage message = session 64 .createTextMessage("ActiveMq 发送的消息" + i); 65 // 发送消息到目的地方 66 System.out.println("发送消息:" + "ActiveMq 发送的消息" + i); 67 producer.send(message); 68 } 69 } 70 }